我想检查一个对象是否具有某物的属性并且其值是否等于某个值。
var test = [{name : "joey", age: 15}, {name: "hell", age: 12}]
就是这样,一个对象数组,现在我想在对象内部进行搜索,如果该对象包含我想要的内容,则返回 true。
我尝试这样做:
Object.prototype.inObject = function(key, value) {
if (this.hasOwnProperty(key) && this[key] === value) {
return true
};
return false;
};
这可以工作,但不能在数组中。我怎么做?
Use the some数组法 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some测试数组中每个值的函数:
function hasValue(obj, key, value) {
return obj.hasOwnProperty(key) && obj[key] === value;
}
var test = [{name : "joey", age: 15}, {name: "hell", age: 12}]
console.log(test.some(function(boy) { return hasValue(boy, "age", 12); }));
// => true - there is a twelve-year-old boy in the array
Btw, 不要延长Object.prototype https://stackoverflow.com/questions/13296340/how-to-define-method-in-javascript-on-array-prototype-and-object-prototype-so-th.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)