如何在JavaScript中将函数的输出添加到数组中

时间:2012-10-23 07:29:26

标签: javascript

我几次遇到这个问题。如何将函数的输出而不是函数本身添加到JavaScript中的数组中。请考虑以下事项:

function getRandomValue(){
  returns a random number
}

myArray = [getRandomValue(), getRandomValue()];

是否可以只将随机数而不是函数本身添加到数组中?

4 个答案:

答案 0 :(得分:1)

你拥有的已经使用函数的返回值填充数组:

function getRandomValue(){
    //returns a random number
}

var myArray = [getRandomValue(), getRandomValue()]; // Call the function
var myArray2 = [getRandomValue, getRandomValue]; // Reference to the function

标识符后面的括号会导致调用该函数,并且它的返回值将被放置在数组的相应索引处。

如果你要删除如上所示的调用括号,你将使用对函数的引用来填充数组,而不是它返回的值。

答案 1 :(得分:0)

您可以使用变量。

var a = getRandomValue();
var b = getRandomValue();
myArray = [a,b];

但是,正如在注释中所说,当你在数组中调用函数时,你将结果放在数组中,而不是函数本身。所以你的行为与我的解决方案完全相同。

答案 2 :(得分:0)

试试这个: 如果你想要一个以上的值,就把它放到一个循环中。

var myArray= [];
console.log(myArray.push(Math.random()));

答案 3 :(得分:-1)

另一种方法是使用array_push函数:

myarray.push(getRandomValue());