为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

喵喔喔 2021-04-26 04:08:04
我在理解此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 arrayelse  return contents of array and color added to an empty array我要关闭还是要离开?
查看完整描述

2 回答

?
繁星点点滴滴

TA贡献1803条经验 获得超3个赞

试图用评论进行解释,希望这会有所帮助。


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集

查看完整回答
反对 回复 2021-05-06
?
慕沐林林

TA贡献2016条经验 获得超9个赞

它将数组减少到其唯一值。您可以将其读取为:

设置distinct为空数组(第二个参数减少)。对于colorin中的每个colors,如果colorin中的distinct索引(!== -1),则更新distinctdistinct(no-op)(第一个三进制分支);否则,如果colorin中不存在distinct,则更新distinctdistinctcolor(第2个三进制分支)。

请参阅mdn reduce文档。


查看完整回答
反对 回复 2021-05-06
  • 2 回答
  • 0 关注
  • 189 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信