包含属性的数组中的IndexOf

IndexOf in an array that contains attributes

本文关键字:IndexOf 数组 包含 属性      更新时间:2023-09-26

我的问题不同:

我使用的是angular/javascript,我想知道一个值是否存在于数组中。下面是我的代码:

    var source = [1, 2, 3 , 4 , 5]; 
    var cities = [{ city: 4 }, { city: 6 }, { city: 8 }]; 
    angular.forEach(source, function (value, key) { 
    if (cities["city"].indexOf(value) != -1) { 
         console.log(value+ " exist"); } 
   else{ console.log(value+ " not exist"); }
 });

,但城市["city"]不是未定义的。有什么帮助吗?

由于它是一个数组,因此需要使用索引来访问元素,如下所示:

var firstCity = cities[0];
console.log(firstCity["city"]);

如果这是javascript, ECMAScript 6将包含一个数组。Find方法,但对于旧版本,你只需要循环遍历城市并使用cities[n]测试每个城市。

您的cities数组包含3个元素。您必须遍历它们,并检查其中是否有包含所查找的值。假设您正在使用javascript,因为console.log,您可以这样做。

cities["city"]是未定义的,因为cities是一个仅包含0、1和2作为索引(cities[0]cities[1]cities[2])的数组。这三个是索引为"city"的,比如cities[0]["city"]

var source = [1,2,3,4,5];
for (var i = 0; i < source.length; i++) {
   var found = false;
   for (var j = 0; j < cities.length; j++) {
      if (cities[j]["city"] === i) {
          found = true;
      }
   }
   if (found) {
      console.log(i + " exists");
   } else {
      console.log(i + " not exists");
   }
}

我建议用对象遍历数组。

var source = [1, 2, 3, 4, 5];
var cities = [{ city: 4 }, { city: 6 }, { city: 8 }];
source.forEach(function (a) {
    if (cities.some(function (aa) { return aa.city === a; })) {
        document.write(a + ' exist<br>');
    } else {
        document.write(a + ' does not exist<br>');
    }
});

奖励:根据最初的问题,一些使用Array.prototype.indexOf的想法。

var city42 = { city: 42 };
var cities = [{ city: 4 }, { city: 6 }, { city: 8 }, city42];
document.write(cities.indexOf({ city: 8 }) + '<br>'); // -1 does not work
document.write(cities.indexOf(city42) + '<br>'); // 3 does work
var index = -1;
cities.some(function (a, i) {
    return a.city === 8 && ~(index = i);
});
document.write(index + '<br>'); // 2