繁体   English   中英

JavaScript函数返回数组

[英]JavaScript function to returning array

我有以下代码:

var disArray = ['red','red','green','green','green','blue','blue','blue','blue','blue'];
var otherArray = [];


function takeOut() {
    for ( i = 0; i < 3; i++ ) {
        var randItem = disArray[Math.floor(Math.random()*disArray.length)];
        otherArray.push(randItem);
    }
    return otherArray;
}

takeOut(disArray)
console.log(otherArray)

我希望函数在被调用时返回otherArray的元素,但出现错误undefined 它仅在我console.log otherArrayotherArray 有什么方法可以使函数不使用console.log返回数组?

您可以使用局部变量。

 function takeOut() { var otherArray = [], i, randItem; for (i = 0; i < 3; i++ ) { randItem = disArray[Math.floor(Math.random() * disArray.length)]; otherArray.push(randItem); } return otherArray; } var disArray = ['red','red','green','green','green','blue','blue','blue','blue','blue'], result = takeOut(disArray); console.log(result); 

对于可重用的函数,可以向该函数添加一些参数,例如需要的数组和计数。

 function takeOut(array, count) { var result = []; while (count--) { result.push(array[Math.floor(Math.random() * array.length)]); } return result; } var disArray = ['red','red','green','green','green','blue','blue','blue','blue','blue'], result = takeOut(disArray, 5); console.log(result); 

多次调用takeOut并将结果存储在数组中的示例。

 function takeOut(array, count) { var result = []; while (count--) { result.push(array[Math.floor(Math.random() * array.length)]); } return result; } var disArray = ['red','red','green','green','green','blue','blue','blue','blue','blue'], i = 7, result = [] while (i--) { result.push(takeOut(disArray, 5)); } console.log(result); 

基本上,对takeOut()的调用是使用return返回值。 如果要在控制台上打印,则需要将其传递到console.log()fn。 另一种方法是分配fn调用,即。 takeOut()到变量并将变量定向到控制台或在其他地方使用。

 var disArray = ['red','red','green','green','green','blue','blue','blue','blue','blue']; var otherArray = []; function takeOut() { for ( i = 0; i < 3; i++ ) { var randItem = disArray[Math.floor(Math.random()*disArray.length)]; otherArray.push(randItem); } return otherArray; } takeOut() //need to utilize the returned variable somewhere. console.log(takeOut()) //prints to stackoverflow.com result // inspect browser console 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM