2015-11-12 53 views
1

下面是解决方案leetcode的组合问题https://leetcode.com/problems/combinations/。基本上,n选择k,返回所有可能性。我遇到了我的第二个for循环,你看javascript array.push(array.push(x))奇怪的结果

tmpResult[i].push(n); 
result.push(tmpResult[i]); 

,如果我做

result.push(tmpResult[i].push(n)); 

内这个问题的结果是非常不同的,我得到一个错误:22 线:类型错误:tmpResult [我] .push不是一个函数。 我来自java的世界,什么是JavaScript做不同的行代码不同于上面的2行?

var combine = function(n, k) { 
    if (k === 0 || k > n) 
     return []; 

    var result = []; 

    if (k === 1) { 
     for (var i = 1; i <= n; i++) { 
      result.push([i]); 
     } 
     return result; 
    } 
    // choose n 
    var tmpResult = combine(n-1,k-1); 

    for(var i = 0; i < tmpResult.length; i++) { 
     tmpResult[i].push(n); 
     result.push(tmpResult[i]); 
     // below doesnt work 
     // result.push(tmpResult[i].push(n)); 
    } 

    // not choose n 
    result = result.concat(combine(n-1, k)); 

    return result; 
}; 

回答

0

Array.prototype.push()

The push() method adds one or more elements to the end of an array and returns the new length of the array.

要添加的阵列来result的长度,这就是为什么result.push(tmpResult[i].push(n));不起作用。

+0

谢谢,我应该更仔细地看过api! –

0

方法push返回数组的新大小,而不是数组本身

+0

谢谢,我应该更仔细地看过api! –