【发布时间】: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)]' -
那个参数的初始值被格式化(缩进)真的很奇怪。