2017-01-19 21 views
2

我試圖從不同函數返回多個值。 起點是一個二維數組。代碼示例如下:Javascript:從不同函數返回多個值

var items = [[0,1],[1,2],[0,2]]; 
var a; 
var b; 

function first() { 
a = items[Math.floor(Math.random() * items.length)]; 
return a; 
} 

function second() { 
b = a[Math.floor(Math.random() * 2)]; 
return b; 
} 

function third(){ 
    first(); 
    second(); 
} 

third(); 

如果我在代碼之外編寫代碼,一切正常。當我使用函數並用console.log替換return時,它可以工作。如果我使用函數並返回(如上面所報告的代碼),它給我沒有定義。我沒有找到解決方案。爲什麼代碼不工作?

在此先感謝

+0

什麼給你undefined?你想要第三個()做什麼? – AshBringer

+0

在執行'third()'後定義'a'和'b'。 –

+3

你的函數返回的值是正確的,但你沒有對值做任何事情。你想要對價值做什麼? –

回答

1

如果要第三個返回值,請在其中添加一個返回值。

function third(){ 
    var a = []; 
    a.push(first()) 
    a.push(second()) 
    return a; 
} 
1

也許你想要的東西,像

function third(){ 
    return {a: first(), b: second()}; 
} 

然後

var t = third() 
console.log(t.a, t.b) 

,或者如果你在運行ES6

var {a,b} = third() 
console.log(a, b) 

看到解構賦值進一步的細節

2

如果你聲明變量a和b函數外(比如在你的代碼中)比不需要返回值。 a和b將被定義。 但是,如果你沒有在外面聲明它,然後將返回值存儲在數組變量中。

var items = [[0,1],[1,2],[0,2]]; 

function first() { 
a = items[Math.floor(Math.random() * items.length)]; 
return a; 
} 

function second() { 
b = a[Math.floor(Math.random() * 2)]; 
return b; 
} 

function third(){ 
var a = first(); 
var b = second(); 
var arr = []; 
arr.push(a); 
arr.push(b); 
return arr 
} 

var t = third(); 
console.log(t[0], t[1]);