【问题标题】:flattening an array: where does the 0 come from?展平数组:0 来自哪里?
【发布时间】: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


    【解决方案1】:

    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);
    }, []);
    

    这是错误的。

    另请注意,您的两个解决方案实际上都不会展平二维以上的数组。

    【讨论】:

    • 现在我看到0 来自哪里,它来自索引
    【解决方案2】:

    .concat() 连接.reduce(function(a,b,index,array) {}) 处的所有参数

    【讨论】:

      【解决方案3】:

      在这种情况下不需要 reduce,只需将 const 连接到新的 const 或 var。

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

      虽然想了解此问题的学术部分是勇敢的,但您最好了解基类方法本身的基本用法,因为它们的构建是为了帮助冗余用例而无需耦合/嵌套/链接大部分。

      【讨论】:

      • 他在问为什么它输出 0。
      • 是的,但这不是代码挑战:挑战是填写/* your code here ... */
      • 我想我对代码挑战的有用性及其务实的用法或措辞印象更深。它说不能使用任何函数,但用户的第一个参数是对超类方法的调用。如果我没有在参数中声明任何内容而只是将值分配给我的 var,我的错误怎么办?
      • @BrianEllis 这很有帮助。同意代码挑战绝对不实用,并且您的代码更好。
      • 关于您回答的编辑:我认为这里没有任何超类化。
      猜你喜欢
      • 2020-12-26
      • 1970-01-01
      • 2022-09-17
      • 1970-01-01
      • 2010-09-21
      • 1970-01-01
      • 2014-04-24
      • 2015-07-13
      • 1970-01-01
      相关资源
      最近更新 更多