Javascript 展平数组:0从何而来?

Javascript 展平数组:0从何而来?,javascript,arrays,function,function.prototype,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 c

此挑战是在不定义任何新函数的情况下展平阵列:

// 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会为展平的
产生不同的值?

在这种情况下,不需要将常数简化为新的常数或变量

const arr = [1, [2]];
var arrFlat = [].concat.apply([], arr);
console.log(arrFlat);

如果你想了解这个问题的学术部分,那么你最好了解基类方法本身的基本用法,因为基类方法是为了帮助冗余用例而构建的,在大多数情况下不需要耦合/嵌套/链接。

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);
}, []);
这是错误的


还要注意的是,两种解决方案实际上并没有展平二维以上的数组。

.concat()
处的所有参数串联在一起。reduce(函数(a,b,index,array){}
他问它为什么输出0.true,但这不是代码挑战:挑战是在这里填写
/*您的代码*/我想我更多的是对代码挑战的有用性及其实用用法或措辞的印象。它说不能使用任何函数,但用户的第一个参数是对超类方法的调用。如果我没有在参数中声明任何内容,只是将值赋给我的var,我的怎么会错呢?@BrianEllis这很有帮助。同意代码挑战绝对不实用,并且您的代码更好。关于对您答案的编辑:我不认为这里有任何超分类。现在我看到
0
来自何处,它来自索引