[英]Compare property value in an array of objects
你好我正在一个项目中继续学习这个URL中的js: http : //themapapp.herokuapp.com/这是github页面: https : //github.com/xtatanx/mapApp
在我的代码的一些部分中,我需要检查一个对象数组中是否已经存在某个属性,而且我的属性值是等于某个东西,到目前为止,我用来代码的代码就是这个:
// check if property value exist in an array of objects
function searchByValue(value, property, array){
for(var i = 0; i < array.length; i++){
if(array[i][property] === value){
return true;
}
}
return false;
}
我这样使用它:
if(searchByValue('myDestiny', 'id', map.markers)){
map.markers[1].setPosition({
lat: results[0].geometry.location.k,
lng: results[0].geometry.location.A
});
}else{
createMarker(results[0].geometry.location.k, results[0].geometry.location.A, 'myDestiny');
我的问题是,如果我实际上是这样做的,或者我错了,因为我有时认为它的功能没有返回正确的值或者工作不正常,如果你们中的一些人能给我一些建议,我将不胜感激在如何实现这一目标,或改进它。
编辑
我完成了类似的事情
Array.prototype.searchBy = function(property, value){
var _property = arguments[0];
var _value = arguments[1];
if(arguments.length === 1){
return Array.prototype.indexOf.apply(this, arguments);
}
for(var i = 0; i < this.length; i++){
if(this[i][_property] === _value ){
return true;
}
}
return false;
};
没有使用checkprop部分,因为实际上并不了解它是如何工作的o_O。 非常感谢@GameAlchemist和@jshanley
只要您搜索的数组中的每个对象都定义了您检查的属性,您的代码就能正常工作。 我可以看到遇到问题。 在尝试访问其值之前,您可以尝试添加检查属性的检查,如下所示:
function searchByValue(value, property, array){
for(var i = 0; i < array.length; i++){
// check that property is defined first
if(typeof array[i][property] !== 'undefined') {
// then check its value
if(array[i][property] === value){
return true;
}
}
}
return false;
}
我宁愿将此函数定义为Array的一个方法,为什么不重载indexOf,它将作为带有一个参数的std indexOf,并作为带有三个参数的indexOf(value,propertyName,checkProp)。
var __oldIndexOf = Array.prototype.indexOf ;
Array.prototype.indexOf = function() {
if (arguments.length==1) return __oldIndexOf.apply(this, arguments);
var value = arguments[0];
var property = arguments[1];
var checkProp = arguments[2];
if (!checkProp) {
for(var i = 0; i < this.length; i++){
if(this[i][property] === value){
return i;
}
} else {
for(var i = 0; i < this.length; i++){
var thisItem = this[i] ;
if (!Object.hasOwnProperty(thisItem, property))
throw('indexOf error : object ' + thisItem + ' has no property ' + property);
if(this[i][property] === value){
return i;
}
}
return -1;
};
所以,对于你的代码,
if (searchByValue('myDestiny', 'id', map.markers)) { ...
成为:
if (map.markers.indexOf('myDestiny', 'id') != -1 ) { ...
显然,您可以存储找到的索引,以备不时之需。
我认为,在你的情况下,你的意思是使用找到的索引:
var destinyIndex = map.markers.indexOf('myDestiny', 'id');
if(destinyIndex != -1){
map.markers[ destinyIndex ].setPosition({
lat: results[0].geometry.location.k,
lng: results[0].geometry.location.A
});
} else {
createMarker(results[0].geometry.location.k, results[0].geometry.location.A,
'myDestiny');
}
编辑:检查该属性存在的想法是由@jshanley提供的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.