gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 06:42:29 24 4
gpt4 key购买 nike

下面是leetcode组合问题的解决方案https://leetcode.com/problems/combinations/ 。基本上,n 选择 k,返回所有可能性。我在第二个 for 循环中遇到了这个问题,你可以看到

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

如果我愿意

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

结果非常不同,我收到一个错误:第 22 行:TypeError:tmpResult[i].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;
};

最佳答案

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)); 不会工作。

关于javascript array.push(array.push(x)) 奇怪的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33669977/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com