var king = [1,2,3,4];
var kong = [55,77];
var thor = king.map(function(num) { return num + 1 });
var pan = king.map(function(num) { return kong.push(num) });
console.log(kong); // [55, 77, 1, 2, 3, 4]
console.log(thor); // [2, 3, 4, 5]
console.log(pan); // [3, 4, 5, 6] ??
我以为我明白 .map 在做什么,但是在尝试之后,我发现了一个让我困惑的结果。对于console.log(pan)的结果,我期待的是:
[[55, 77, 1], [55, 77, 1, 2], [55, 77, 1, 2, 3], [55, 77, 1, 2, 3, 4]]
但是,结果是:
[3, 4, 5, 6]
看起来它正在返回每个结果数组的长度?困惑。
最佳答案
来自the MDN :
The push() method adds one or more elements to the end of an array and returns the new length of the array.
你有一个长度数组。
这是您似乎想要的实现(不改变 kong 因为功能总是感觉更好):
var pan = king.reduce(function(arr, num) {
arr.push((arr[arr.length-1]||kong).concat(num));
return arr
}, []);
关于javascript - .map 返回每次迭代结果数组的长度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38484286/