【发布时间】:2017-02-24 19:10:12
【问题描述】:
这个挑战是在不定义任何新函数的情况下展平数组:
// 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 产生不同的值?
【问题讨论】:
标签: javascript arrays function function.prototype