array.push() 方法没有向数组添加任何内容并且工作异常
array.push() method is not adding anything to array and working weirdly
我是编程新手,也是 Whosebug。
我的问题与 JavaScript
中的 array.push()
方法有关。
先看代码
var buttonColors = ["red", "blue", "green", "yellow"];
var gamePattern = [];
gamePattern = gamePattern.push(nextSequence());
function nextSequence(){
var randomNumber = Math.floor( Math.random() * 4);
var randomChosenColor = buttonColors[randomNumber];
return randomChosenColor;
}
也请检查这张图片...
This is chrome console output
问题是 randomNumber
生成正确,randomChosenColor
也正确获取颜色,但它没有被推入 gamePattern
数组的行号 [=24] =]3。如果有其他方法可以替代此方法,也请帮助我。
push()
改变原始数组(和 returns 新长度),因此您不需要为 gamePattern
分配新值。尝试这样的事情:
var buttonColors = ["red", "blue", "green", "yellow"];
var gamePattern = [];
gamePattern.push(nextSequence());
function nextSequence(){
var randomNumber = Math.floor(Math.random() * 4);
var randomChosenColor = buttonColors[randomNumber];
return randomChosenColor;
}
Push改变了数组的原始状态。所以你不需要重新初始化数组。
var buttonColors = ["red", "blue", "green", "yellow"];
let temp=[];
temp.push(seq());
console.log(temp);
function seq(){
var randomNumber = Math.floor( Math.random() * 4);
var randomChosenColor = buttonColors[randomNumber];
return randomChosenColor;
}
我是编程新手,也是 Whosebug。
我的问题与 JavaScript
中的 array.push()
方法有关。
先看代码
var buttonColors = ["red", "blue", "green", "yellow"];
var gamePattern = [];
gamePattern = gamePattern.push(nextSequence());
function nextSequence(){
var randomNumber = Math.floor( Math.random() * 4);
var randomChosenColor = buttonColors[randomNumber];
return randomChosenColor;
}
也请检查这张图片... This is chrome console output
问题是 randomNumber
生成正确,randomChosenColor
也正确获取颜色,但它没有被推入 gamePattern
数组的行号 [=24] =]3。如果有其他方法可以替代此方法,也请帮助我。
push()
改变原始数组(和 returns 新长度),因此您不需要为 gamePattern
分配新值。尝试这样的事情:
var buttonColors = ["red", "blue", "green", "yellow"];
var gamePattern = [];
gamePattern.push(nextSequence());
function nextSequence(){
var randomNumber = Math.floor(Math.random() * 4);
var randomChosenColor = buttonColors[randomNumber];
return randomChosenColor;
}
Push改变了数组的原始状态。所以你不需要重新初始化数组。
var buttonColors = ["red", "blue", "green", "yellow"];
let temp=[];
temp.push(seq());
console.log(temp);
function seq(){
var randomNumber = Math.floor( Math.random() * 4);
var randomChosenColor = buttonColors[randomNumber];
return randomChosenColor;
}