【发布时间】:2014-06-02 00:43:19
【问题描述】:
您好,我正在从事一个项目以继续学习 js,网址为:http://themapapp.herokuapp.com/,这是 github 页面:https://github.com/xtatanx/mapApp
在我的代码的某些部分中,我需要检查某个属性是否已经存在于对象数组中,并且我该属性值是否等于某个值,到目前为止,我用来 dis 的代码就是这个:
// 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
【问题讨论】:
标签: javascript arrays node.js object for-loop