javascript array.push(array.push(x)) 奇怪的结果
javascript array.push(array.push(x)) weird result
下面是leetcode的组合题https://leetcode.com/problems/combinations/的解法。基本上,n选择k,return所有的可能性。我 运行 在我的第二个 for 循环中遇到了这个问题
tmpResult[i].push(n);
result.push(tmpResult[i]);
如果我这样做
result.push(tmpResult[i].push(n));
结果非常不同,我得到一个错误:
第 22 行:类型错误:tmpResult[i].push 不是函数。
我来自 java 世界,javascript 在不同于上面两行的那一行代码中有什么不同?
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;
};
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));
不起作用的原因。
方法推送returns数组的新大小,而不是数组本身
下面是leetcode的组合题https://leetcode.com/problems/combinations/的解法。基本上,n选择k,return所有的可能性。我 运行 在我的第二个 for 循环中遇到了这个问题
tmpResult[i].push(n);
result.push(tmpResult[i]);
如果我这样做
result.push(tmpResult[i].push(n));
结果非常不同,我得到一个错误: 第 22 行:类型错误:tmpResult[i].push 不是函数。 我来自 java 世界,javascript 在不同于上面两行的那一行代码中有什么不同?
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;
};
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));
不起作用的原因。
方法推送returns数组的新大小,而不是数组本身