使用一行if语句进行归约和扩展函数背后的逻辑

我在理解此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


我要关闭还是要离开?


喵喔喔
浏览 190回答 2
2回答

繁星点点滴滴

试图用评论进行解释,希望这会有所帮助。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集

慕沐林林

它将数组减少到其唯一值。您可以将其读取为:设置distinct为空数组(第二个参数减少)。对于colorin中的每个colors,如果colorin中的distinct索引(!== -1),则更新distinct为distinct(no-op)(第一个三进制分支);否则,如果colorin中不存在distinct,则更新distinct为distinct+ color(第2个三进制分支)。请参阅mdn reduce文档。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript