如何将匿名函数的值返回到数组中。我试过这个代码,但它不起作用。哪里错了
for (var i = 0; i < num; i++) {
//get ramdom color
// arr.push(randomColor());
arr.push(function() {
//pick a "red" from 0 - 255
var r = Math.floor(Math.random() * 256);
//green 0 - 255
var g = Math.floor(Math.random() * 256);
//blue 0 -255
var b = Math.floor(Math.random() * 256);
return "rgb" + "(" + r + ", " + g + ", " + b + ")";
});
}
答案 0 :(得分:2)
无需复杂化:
for (var i = 0; i < num; i++) {
//get ramdom color
//pick a "red" from 0 - 255
var r = Math.floor(Math.random() * 256);
//green 0 - 255
var g = Math.floor(Math.random() * 256);
//blue 0 -255
var b = Math.floor(Math.random() * 256);
var colour = "rgb" + "(" + r + ", " + g + ", " + b + ")";
arr.push(colour)
}
答案 1 :(得分:1)
以下是你如何做到的:
for (var i = 0; i < num; i++) {
//get ramdom color
// arr.push(randomColor());
arr.push(function() {
//pick a "red" from 0 - 255
var r = Math.floor(Math.random() * 256);
//green 0 - 255
var g = Math.floor(Math.random() * 256);
//blue 0 -255
var b = Math.floor(Math.random() * 256);
return "rgb" + "(" + r + ", " + g + ", " + b + ")";
}()); // Note the two brackets.
}
注意最后一行的两个括号。它们意味着立即执行该功能。
虽然要小心这样的模式。很容易将读者与这些代码混淆。您可能更喜欢使用以下内容:
function getRandomColor() {
//pick a "red" from 0 - 255
var r = Math.floor(Math.random() * 256);
//green 0 - 255
var g = Math.floor(Math.random() * 256);
//blue 0 -255
var b = Math.floor(Math.random() * 256);
return "rgb" + "(" + r + ", " + g + ", " + b + ")";
}
for (var i = 0; i < num; i++) {
//get ramdom color
// arr.push(randomColor());
arr.push(getRandomColor());
}
答案 2 :(得分:1)
你没有在循环中调用这些函数。
let arr = [];
let num = 3;
for (let i = 0; i < num; i++) {
arr.push((() => {
let r = Math.floor(Math.random() * 256);
let g = Math.floor(Math.random() * 256);
let b = Math.floor(Math.random() * 256);
return "rgb" + "(" + r + ", " + g + ", " + b + ")";
})());
}
console.log(arr);