搜索数组

推荐的方法(自 ES5 起)是使用 Array.prototype.find

let people = [
  { name: "bob" },
  { name: "john" }
];

let bob = people.find(person => person.name === "bob");

// Or, more verbose
let bob = people.find(function(person) {
  return person.name === "bob";
});

在任何版本的 JavaScript 中,也可以使用标准的 for 循环:

for (var i = 0; i < people.length; i++) {
  if (people[i].name === "bob") {
    break; // we found bob
  }
}

FindIndex

所述 findIndex() 方法在数组中返回一个索引,如果阵列中的一个元素满足提供的测试功能。否则返回 -1。

array = [
  { value: 1 },
  { value: 2 },
  { value: 3 },
  { value: 4 },
  { value: 5 }
];
var index = array.findIndex(item => item.value === 3); // 2
var index = array.findIndex(item => item.value === 12); // -1