Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
循环javascript函数并将结果推送到数组中_Javascript_Arrays_For Loop - Fatal编程技术网

循环javascript函数并将结果推送到数组中

循环javascript函数并将结果推送到数组中,javascript,arrays,for-loop,Javascript,Arrays,For Loop,我真是束手无策。也许有人能给我们点启示。 我基本上是尝试使用for循环运行函数10x,然后将结果推送到数组中。然而,我得到的只是数组中的十个“未定义”。函数的实际解析值未推入数组。有人有主意吗 这是密码 函数游戏(){ var userChoice=getUserChoice('rock'); var computerChoice=getComputerChoice(); log(determineWinner(userChoice,computerChoice)); }; 函数keepSco

我真是束手无策。也许有人能给我们点启示。 我基本上是尝试使用for循环运行函数10x,然后将结果推送到数组中。然而,我得到的只是数组中的十个“未定义”。函数的实际解析值未推入数组。有人有主意吗

这是密码

函数游戏(){
var userChoice=getUserChoice('rock');
var computerChoice=getComputerChoice();
log(determineWinner(userChoice,computerChoice));
};
函数keepScore(){
设resultArray=[];
for(设x=0;x<10;x++){
结果推送(游戏(x))
}
console.log(resultArray);
};

keepScore()调用push时,需要指定要推送的元素。但是,您正在调用play game函数,该函数不返回任何元素。您应该明确指定游戏中要返回的元素,它应该可以工作

function playGame(){
 var userChoice = getUserChoice('rock');
 var computerChoice = getComputerChoice();
 
  return determineWinner(userChoice,computerChoice);
};

您需要返回
determineWinner(userChoice,computerChoice)

现在,函数只返回
undefined


因此,只需添加
returndeterminewinner(userChoice,computerChoice),你应该没事。

这应该行得通。这里的主要任务是
返回所需的值。添加的代码只是为了使代码段正常工作

函数游戏(){
var选项=['rock'、'paper'、'scissor'];
var userChoice=window.prompt(“石头、布、剪刀”);
var computerChoice=options[(数学地板(数学随机()*3+1)-1)];
var arr=[userChoice,computerChoice];
日志(userChoice,computerChoice);
返回(arr);
};
函数keepScore(){
var resultArray=[];
for(设x=0;x<10;x++){
结果推送(游戏(x))
}
console.log(resultArray);
};

keepScore()
playGame()
中需要一个return语句,我可能会添加函数getComputerChoice()生成值。当我运行一个简单的for循环时,我得到十个字符串。每当我尝试将它们放入数组时,我会得到10倍的未定义值。干杯@RandyCasburn它现在可以工作了
playGame
需要
返回determineWinner(userChoice,computerChoice)
而不是仅仅记录它。@Barmar。啊,现在明白了。非常感谢你!3 - 1 + 1? 也称为3:););)