2016-08-17 175 views
0

我有以下代码:JavaScript函数返回数组

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.logotherArray。有什么办法可以让我的函数返回数组而不使用console.log

+1

otherArray =取出(混乱); console.log(otherArray); – user2249160

+1

'otherArray'不在函数的范围内。 –

+0

'undefined'不是错误。你甚至没有任何错误。 – Xufox

回答

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

+0

更具体地说,你正在使用'takeOut()'的返回值并将它传递给'console.log'。 –

+0

没错。结果集现在独立于前一个变量'otherArray'。 –

+0

您还应该在函数声明中添加'disArray'作为参数,以便它可以使用任何数组作为参数,而不仅仅是全局。现在传递'takeOut()'参数什么也不做。 – 4castle

-1

基本上以取出()的调用将返回使用返回的值。如果要在控制台上打印,则需要将其传递给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