这个挑战就是击败阵列时不定义任何新的功能:展平数组:0从哪里来?
// 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]
我的节点,Chrome和杉木测试efox并获得了相同的结果。
那么0来自何处?为什么解决方案1和解决方案2产生flattened
的不同值?
现在我看到'0'来自哪里,它来自索引 –