我有一个字符串数组,只需要将其中的4个(随机)放入另一个数组中。
var a = ["Orange", "Red", "Yellow", "Blue", "Black", "White", "Brown", "Green"];
var b = [];
function selectColours(){
var toRandomise = a[Math.floor(Math.random() * 4)];
b.push(toRandomise);
}
console.log(b);
我的问题是控制台没有显示任何内容。
答案 0 :(得分:3)
好吧,你并没有真正运行你创建的功能。简单地宣布它。
只需在selectColors();
console.log
即可
答案 1 :(得分:2)
您还需要添加4次随机值,以便您可以使用for循环
var a = ["Orange", "Red", "Yellow", "Blue", "Black", "White", "Brown", "Green"];
var b = [];
function selectColours() {
for (var i = 0; i < 4; i++) {
var toRandomise = a[Math.floor(Math.random() * 4)];
b.push(toRandomise);
}
}
selectColours()
console.log(b);
您也可以使用递归。
var a = ["Orange", "Red", "Yellow", "Blue", "Black", "White", "Brown", "Green"];
var b = [], count = 0;
function selectColours() {
if (count == 4) return true;
b.push(a[Math.floor(Math.random() * 4)]);
count++;
selectColours();
}
selectColours()
console.log(b);