确定对象在javascript中是否具有属性和值

Joe*_*ito 23 javascript jquery web

我想检查一个对象是否具有某个属性,并且其值等于某个值.

var test = [{name : "joey", age: 15}, {name: "hell", age: 12}]
Run Code Online (Sandbox Code Playgroud)

你去,一个对象数组,现在我想在对象内搜索,如果对象包含我想要的东西,则返回true.

我试着这样做:

Object.prototype.inObject = function(key, value) {
if (this.hasOwnProperty(key) && this[key] === value) {
  return true
};
return false;
};
Run Code Online (Sandbox Code Playgroud)

这可行,但不在数组中.我怎么做?

Ber*_*rgi 32

使用someArray方法测试数组的每个值的函数:

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
Run Code Online (Sandbox Code Playgroud)

顺便说一句,不要延长Object.prototype.

  • @Ecropolis:但是可以简单地调整,请参阅链接文档的"polyfill"部分 (3认同)

bor*_*nac 5

——对于房产——

if(prop in Obj)  
//or
Obj.hasOwnProperty(prop)
Run Code Online (Sandbox Code Playgroud)

-- 为价值 --

使用 "Object.prototype.hasValue = ..." 对 js 来说是致命的,但Object.defineProperty允许你使用enumerable:false (默认) 定义属性

Object.defineProperty(Object.prototype,"hasValue",{
   value : function (obj){
              var $=this;
              for( prop in $ ){
                  if( $[prop] === obj ) return prop;
              }
              return false;
           }
});
Run Code Online (Sandbox Code Playgroud)

仅用于实验测试 NodeList 是否具有 Element

var NL=document.QuerySelectorAll("[atr_name]"),
    EL= document.getElementById("an_id");
console.log( NL.hasValue(EL) )  

// if false then #an_id has not atr_name
Run Code Online (Sandbox Code Playgroud)