I am new to programming and also stackoverflow . My problem is related to array.push()
method in JavaScript
. See the code first
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;
}
Kindly check this image too... This is chrome console output
The problem is that the randomNumber
is being generated properly and randomChosenColor
is also getting the color properly but it is not being pushed in gamePattern
array at line number 3 . Also help me if there is some alternative to this method.
Push changes the original state of the array. So you don't need to re-initialize the array.
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;
}
push()
mutates the original array (and returns the new length), so you don't need to assign a new value to gamePattern
. Try something like this:
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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.