javascript - 展平数组 : where does the 0 come from?

标签 javascript arrays function function.prototype

这个挑战是在不定义任何新函数的情况下展平数组:

// challenge
const arr = [1, [2]]
const flattened = arr.reduce(/*your code here, no function expressions or declarations allowed*/, [])
console.log(flattened) // expected: [1, 2]

我的解决方案不起作用,但真正困扰我的是我不知道 0 来自哪里:

// Solution 1
const arr = [1, [2]]
const flattened = arr.reduce(Function.prototype.call.bind(Array.prototype.concat), [])
console.log(flattened) // unexpected result: [1, 0, 1, [1], 2, 1, 1, [1]]

我期望代码的行为如下所示,它按预期工作:

// Solution 2
const arr = [1, [2]]
const flattenReducer = (x, y) => Function.prototype.call.bind(Array.prototype.concat)(x, y)
const flattened = arr.reduce(flattenReducer, [])
console.log(flattened) // logs the expected result: [1, 2]

我在 Node、Chrome 和 Firefox 中进行了测试,得到了相同的结果。

那么 0 是从哪里来的,为什么解决方案 1 和解决方案 2 会为 flattened 产生不同的值?

最佳答案

reduce 的回调不仅有两个参数。实际上它有四个:累加器、当前值、索引和原始数组。

您的解决方案 #1 等同于

arr.reduce(function (x, y, z, a) {
    return Function.prototype.call.bind(Array.prototype.concat)(x, y, z, a);
}, []);

或等效的

arr.reduce(function (x, y, z, a) {
    return x.concat(y, z, a);
}, []);

这是错误的。

另请注意,您的两个解决方案实际上并未展平具有两个以上维度的数组。

关于javascript - 展平数组 : where does the 0 come from?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42446491/

相关文章:

javascript - 在显示新数据之前清除

javascript - 计算 2 个数组中出现了多少个相同的元素

javascript - 在变量中声明一个 JavaScript 函数?

javascript - "flow check-contents"和 "flow suggest"

javascript - 添加 emoji=true 到 .flowconfig

c - 汇编中 C 的数组

ios - 如何解析这种类型的数组?

c++ - 使用类的 Hangman 游戏无法正常工作

c - 返回函数 c 中的结构

javascript - 来自 UL LI 的 JQuery Autocomplete(作为源代码)