【问题标题】:Logic behind reduce and spread function using one line if statement使用一行if语句的reduce和spread函数背后的逻辑
【发布时间】:2019-09-09 02:48:38
【问题描述】:

我在理解这个 reduce 示例的 if 语句时遇到问题:

const colors = ['red', 'red', 'green', 'blue', 'green', 'yellow'];
console.log(colors);

const distinctColors = colors.reduce(
    (distinct, color) =>
        (distinct.indexOf(color) !== -1) ? 
            distinct : 
            [...distinct, color], []
)

console.log(distinctColors)

我试图理解伪代码中的 if 语句,并阅读这个示例,我一直看到如下:


If the color found in the distinct array (which is empty)
  return empty array
else
  return contents of array and color added to an empty array

我是关闭还是关闭?

测试 repl.it here

【问题讨论】:

  • distinct 仅在第一次迭代中为空。更正确的解释是“如果在不同数组中找到颜色,则返回不同数组。否则返回一个包含不同数组元素和颜色的新数组。”。但实际上,您应该只使用const distinctColors = new Set(colors);
  • 现在我倾向于使用 Set const distinctColors = [...new Set(colors)]'
  • 那个参数的初始值被格式化(缩进)真的很奇怪。

标签: javascript spread-syntax


【解决方案1】:

它将数组缩减为唯一值。你可以这样理解:

distinct 设置为一个空数组(要减少的第二个参数)。对于colors 中的每个color,如果colordistinct 中(!== -1 的索引),则将distinct 更新为distinct(无操作)(第一个三元分支),否则如果color 不在distinct 中,将distinct 更新为distinct + color(第二个三元分支)。

请参阅 mdn reduce 文档。

【讨论】:

    【解决方案2】:

    尝试用cmets解释,希望对你有帮助。

    const colors = ['red', 'red', 'green', 'blue', 'green', 'yellow'];
    console.log(colors);
    
    const distinctColors = colors.reduce(
        (distinct, color) =>
            (distinct.indexOf(color) !== -1) ? 
            // ----------------^ Turnary to test for presence of current color in the accum []
                distinct : 
            // ----^ It DOES exist, so return the current Accum array    
                [...distinct, color], []
                // ---^ Is DOES NOT exist, return a new array of Accum + Color
                // --------------------^ This initialises a new empty array into the accumulator
    )
    
    console.log(distinctColors)

    只是添加了这个作为参考,使用一个集合来做这个更有效。

    const colors = ['red', 'red', 'green', 'blue', 'green', 'yellow'];
    console.log(colors);
    
    const distinctColors = [...new Set(colors)];
    
    console.log(distinctColors)

    这是关于 Set 的 MDN 文档。 Javascript Set

    【讨论】:

    • Set 是否默认抓取不同的值?
    • 确实如此。对于更复杂的对象,您可能会使用地图组合。但在这种情况下,您只需要传递数组。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多