javascript array.push(array.push(x)) weird result

时间:2015-11-12 11:03:32

标签: javascript arrays push

below is a solution to leetcode's combination problem https://leetcode.com/problems/combinations/. Basically, n choose k, return all possibilities. I am running into this problem inside my second for loop where you see

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

If i do

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

the result is very different and I get an error: Line 22: TypeError: tmpResult[i].push is not a function. I come from java world and what is javascript doing differently in that one line code that's different from the 2 lines above it?

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

2 个答案:

答案 0 :(得分: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.

You're adding the length of the array to result, which is why result.push(tmpResult[i].push(n)); doesn't work.

答案 1 :(得分:0)

The method push returns the new size of the array, not the array itself