for循环
另一种快速方法是在原型内设置的 for 循环:
let array = [{ prop1: 'value1', }, { prop2: 'value2', }, { prop3: 'value3', }]; Array.prototype.indexOfObject = function (property, value) { for (let i = 0, len = this.length; i < len; i++) { if (this[i][property] === value) return i; } return -1; } console.log(array.indexOfObject("prop2", "value2"));
map()方法
map() 方法创建一个单独的数组并为每个数组元素调用一个函数。
此方法为数组中的每个元素调用一次定义的函数,保持顺序:
let array = [{ prop1: 'value1', }, { prop2: 'value2', }, { prop3: 'value3', }]; function arrayMap() { let pos = array.map(function (e) { return e.prop2; }).indexOf('value2'); console.log("Index of 'value2' is = " + pos); } arrayMap();
JavaScript 中有几种方法可以从对象的数组中访问对象的索引。
查找索引findIndex()方法
我们还可以使用原生且方便的函数 findIndex() ,如下所示:
let myArray= [ { name: 'Jack', age: 25, }, { name: 'Maria', age: 22, }]; let index = myArray.findIndex( element => { if (element.name === 'Maria') { return true; } }); console.log('Maria is at index: ' + index);
如果数组中的元素满足提供的测试函数,则 Array.prototype.findIndex() 方法返回数组中的索引;否则返回-1,表示没有元素通过测试。
它对数组中的每个索引执行一次回调函数,直到找到回调返回 true 的那个。
日期:2020-06-02 22:16:20 来源:oir作者:oir