我是JS的新手,正在尝试学习如何正确地使用JS中的indexOf。也就是说,如果你看下面的代码:
var sandwiches = ['turkey', 'ham', 'turkey', 'tuna', 'pb&j', 'ham', 'turkey', 'tuna'];
var deduped = sandwiches.filter(function (sandwich, index) {
return sandwiches.indexOf(sandwich) === index;
});
// Logs ["turkey", "ham", "tuna", "pb&j"]
console.log(deduped);
我试图去除重复项,但有两个问题想问。首先,在这里 return sandwiches.indexOf(sandwich) === index; 为什么需要使用 "== index"。其次,由于 indexOf 返回索引,如 0、1 或 2 ...,那么为什么当我们 console.log(deduped) 时,我们得到的是名字数组而不是索引数组。希望你明白我的意思。
indexOf
函数返回的值与index
进行比较来实现元素去重呢? - Dickens