JavaScript函数返回数组

时间:2016-08-17 15:34:39

标签: javascript arrays return

我有以下代码:

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 otherArray。有没有什么办法可以让函数在不使用console.log的情况下返回数组?

2 个答案:

答案 0 :(得分:1)

您可以使用本地变量。

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);

答案 1 :(得分:-1)

基本上,对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