包含属性的数组中的IndexOf
IndexOf in an array that contains attributes
我的问题不同:
我使用的是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
相关文章:
- inArray,indexOf在二维数组中
- 为什么空数组上的 indexOf 不返回 -1
- 对象不支持在调用 indexOf 定义的数组时 IE8 中未定义的此属性或方法
- 使用Javascript在mongo中数组indexOf
- Javascript性能:如何在数组中循环并检查每个值比indexOf、search和match更快
- 数组表示形式内的字符串IndexOf
- javascript indexOf 无法检查数组中的相同数字
- JavaScript:Association/Object数组中的indexOf
- Google Sheets/Javascript:无法使用indexOf()在数组中搜索特定字符串
- 在使用JavaScript的IE7/8中,数组上的.indexOf函数不起作用
- 带IndexOf的Undercore reject函数从数组中删除所有对象
- javascript数组indexOf中使用的regex
- 为什么 array.indexOf(undefined) 在数组稀疏的情况下不起作用
- 在数组中查找 indexOf 值
- 如何使用 indexOf 方法检查数组中是否存在“未定义”
- 使用 indexOf 方法在二维数组中查找值
- IndexOf 不能与包含数组的对象一起正常工作
- Javascript Array.indexOf() 在应用于对象数组时表现出奇怪的行为
- JavaScript数组indexOf数组
- javascript indexOf数组在浏览器上的不同结果