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