2016-08-17 15 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に渡す必要があります。もう1つの方法は、fn呼び出しieを割り当てることです。 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

関連する問題