find和findIndex
findIndex() 方法返回传入一个测试条件(函数)符合条件的数组第一个元素位置。
findIndex() 方法为数组中的每个元素都调用一次函数执行:
- 当数组中的元素在测试条件时返回 true 时, findIndex() 返回符合条件的元素的索引位置,之后的值不会再调用执行函数。
- 如果没有符合条件的元素返回 -1
注: findIndex() 对于空数组,函数是不会执行的。
注: findIndex() 并没有改变数组的原始值。
//index.js const arr = [ { title: "es6" }, { title: "webpack", id: 1 }, { title: "vue" }, { title: "webpack", id: 2 }, ]; let result = arr.find(function (item) { return item.title === "webpack"; }); let resultIndex = arr.findIndex(function (item) { return item.title === "webpack"; }); console.log(result, resultIndex);//都返回第一个符合条件的
includes和indexOf
includes(),如果包含则返回true,否则返回false
而
indexOf,如果包含则返回下标,不包含则返回-1
includes比indexOf更清晰