简体   繁体   English

javascript array.push(array.push(x))奇怪的结果

[英]javascript array.push(array.push(x)) weird result

below is a solution to leetcode's combination problem https://leetcode.com/problems/combinations/ . 以下是leetcode组合问题的解决方案https://leetcode.com/problems/combinations/ Basically, n choose k , return all possibilities. 基本上, n选择k ,返回所有可能性。 I am running into this problem inside my second for loop where you see 我在第二个for循环中遇到了这个问题

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. 结果非常不同,我得到一个错误: 第22行:TypeError:tmpResult [i] .push不是一个函数。 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? 我来自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;
};

Array.prototype.push() 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. push()方法将一个或多个元素添加到数组的末尾,并返回数组的新长度。

You're adding the length of the array to result , which is why result.push(tmpResult[i].push(n)); 您要将数组的长度添加到result ,这就是为什么result.push(tmpResult[i].push(n)); doesn't work. 不起作用。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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