作者: 文章来源:
本文原地址:https://www.mimiwuqi.com/webqianduan/196232.html
indexOf和findIndex的区别:
indexOf()主要是用于查找基本数据类型。例如:获取数组中某个元素的下标。findIndex可用于查找复杂数据类型。例如:获取数组里对象的下标。总结:indexOf()方法内部使用的是 全等运算符,如果复合数据类型例如数组里对象,全等运算符就会比较它们的内存地址,如果地址相同,等式才会成立。
因此,当遇到基本数据类型就使用indexOf查询在数组当中的下标。遇到复杂数据类型就用findIndex查询数组对象中的下标。
let arr = [
{a: 1, b:'g', c: false, d: "355"},
{a: 2, b:'s', c: true, d: "854"},
{a: 3, b:'g', c: false, d: "685"},
{a: 4, b:'e', c: false, d: "158"},
{a: 5, b:'g', c: true, d: "444"},
]
let newArr= arr.filter((item,index,arr) =>{
return arr.findIndex(e => e.b==item.b)==index;
});
console.log(newArr);
const arr=[1,4,2,3,5,2,6,8,6,5];
let newArr=[];
arr.forEach((item,index) =>{
if(arr.indexOf(item)==index){
newArr.push(item);
}
})
console.log(newArr); // [1, 4, 2, 3, 5, 6, 8]
更多 建站教程 请访问 https://www.mimiwuqi.com/webqianduan/