gpt4 book ai didi

javascript - 使用filter()返回对象数组的唯一元素

转载 作者:行者123 更新时间:2023-11-27 22:33:04 25 4
gpt4 key购买 nike

我无法生成唯一的数组,不确定使用 filter() 的以下逻辑有什么问题。

https://jsbin.com/mufobevezo/edit?js,console,output

 var uniqueProducts = json.filter(function(elem, i, array) {
return array.indexOf(elem) === i;
}
);

console.log(uniqueProducts);

我从这里获取的代码https://danmartensen.svbtle.com/javascripts-map-reduce-and-filter 。不确定 indexOf 在示例中做什么。

我只是想知道上面的链接是否有错误。

最佳答案

I just want to know if the link above has some mistake.
Not sure what the indexOf do in the example.

好的,让我们看一下代码:

 var uniqueProducts = json.filter(function(elem, i, array) {
return array.indexOf(elem) === i;
}
);

console.log(uniqueProducts);

假设你有这个数组:[5,2,3,5]

filter 函数将运行 4 次。

[5,2,3,5].indexOf(5) === 0;//true ,过滤器将返回 true
[5,2,3,5].indexOf(2) === 1;//true ,过滤器将返回 true
[5,2,3,5].indexOf(3) === 2;//true ,过滤器将返回 true
[5,2,3,5].indexOf(5) === 3;//假(!)。 (5) 的索引是第一个索引,它是 0 ,而不是 3 ,因此函数返回 false 。所以看看刚刚发生了什么,之前找到的元素没有添加到集合中(因此 dup 被删除)。

因此您将拥有的只是 5,2,3 ,这是数组的唯一数字。

更好吗?

关于javascript - 使用filter()返回对象数组的唯一元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39385524/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com