简体   繁体   中英

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

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM