我可以将 array.indexOf() 与 .map() 之类的函数一起使用吗

can I use array.indexOf() with a function like .map()

我正在使用 Extendscript,它使用 ECMAScript 3。所以我受限于许多限制。我正在寻找类似于 Arr.find(func) 但可用于 ECMA3 的东西。因为我需要一种方法来搜索对象数组并找到一个在其属性之一中具有特定值的对象。 所以我发现 Arr.indexOf() 这是 ECMA3 但不确定如何将它与函数一起使用,因为此方法适用于字符串数组。

我的问题是有没有办法将 .indexOf() 与函数(如 .find())一起使用,使其与对象或任何其他解决方案一起使用?

谢谢,

.indexOf() 不会在这里帮助你,因为它只搜索数组。您需要搜索数组内的对象,因此您需要遍历对象并尝试手动查找匹配项。

var objArray = [
  {key1: "foo", key2: true, key3: 10 },
  {key1: "foo2", key2: false, key3: 100 },  
  {key1: "foo3", key2: true, key3: 101, key4: 101 }
];

function findKey(ary, findVal){
  // Loop over the array
  for(var i = 0; i < ary.length; i++){
  
    // Loop over objects keys
    for(var key in ary[i]){
      // Compare current key value against passed value to find
      if(ary[i][key] === findVal){
         console.log(findVal + " was found in object: " + i + ", key: " + key);
      }
    }      
  }
}

findKey(objArray, 101);
findKey(objArray, true);

findIndex 是 Array-function 接受函数而不是值但给出索引。我不熟悉 ExtendScript,但可以添加的 Mozilla 开发人员页面中有一个 polyfill。如果有 map 和 find 那么 findIndex 也可以在那里,但你也可以将 map 和 indexOf 与以下方式结合起来用于一个班轮。

var people = [{name: 'bob', age: 25}, {name: 'mary', age: 5}]
var index = people.map(p => p.name).indexOf('bob')

非常感谢您的所有回答。他们都对我有用。我根据 Scott Marcus 的建议使用了这个函数:

  function findItem(list){
    for (var i=0; i < list.length; i++){
      if (list[i].property === true){return i}
    }
  }