我正在检查一个对象属性是否存在,变量中保存了所要查询的属性名称。
var myObj;
myObj.prop = "exists";
var myProp = "p"+"r"+"o"+"p";
if(myObj.myProp){
alert("yes, i have that property");
};
这是因为它正在寻找 myObj.myProp
但我希望它检查 myObj.prop
我正在检查一个对象属性是否存在,变量中保存了所要查询的属性名称。
var myObj;
myObj.prop = "exists";
var myProp = "p"+"r"+"o"+"p";
if(myObj.myProp){
alert("yes, i have that property");
};
这是因为它正在寻找 myObj.myProp
但我希望它检查 myObj.prop
var myProp = 'prop';
if(myObj.hasOwnProperty(myProp)){
alert("yes, i have that property");
}
或者
var myProp = 'prop';
if(myProp in myObj){
alert("yes, i have that property");
}
或者
if('prop' in myObj){
alert("yes, i have that property");
}
注意,hasOwnProperty
不会检查继承的属性,而 in
会检查。例如,'constructor' in myObj
是 true,但 myObj.hasOwnProperty('constructor')
不是。myObj[myProp]
相比,hasOwnProperty()
更好,因为即使myProp
的值为0,它也能正常工作。 - Matt R'qqq'
拥有'length'
属性,所以返回值为true
,你可以这样做。 - gen_Ericno-prototype-builtins
规则,您应该使用Object.prototype.hasOwnProperty.call(myObj, myProp)
代替myObj.hasOwnProperty(myProp)
。 - Ilyich你可以使用 hasOwnProperty,但根据引用需要在使用该方法时使用引号:
if (myObj.hasOwnProperty('myProp')) {
// do something
}
另一种方法是使用in操作符,但这里也需要引号:
if ('myProp' in myObj) {
// do something
}
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/in
hasOwnProperty()
的实现方式。 - canon感谢大家的帮助和推动,以摆脱eval语句。需要用方括号而不是点符号表示变量。这段代码可以正常工作且代码整洁规范。
这些都是变量:appChoice、underI、underObstr。
if(typeof tData.tonicdata[appChoice][underI][underObstr] !== "undefined"){
//enter code here
}
tData.tonicdata[appChoice]
的结果没有与underI
匹配的属性/索引,那么就会抛出TypeError
。 - Ynot自有财产:
var loan = { amount: 150 };
if(Object.prototype.hasOwnProperty.call(loan, "amount"))
{
//will execute
}
注意:使用 Object.prototype.hasOwnProperty 要比 loan.hasOwnProperty(..) 更好,因为如果原型链中定义了自定义的 hasOwnProperty(这里并没有),会产生影响。var foo = {
hasOwnProperty: function() {
return false;
},
bar: 'Here be dragons'
};
要查找包括继承的属性,请使用in运算符:(但您必须在'in'右侧放置一个对象,原始值会抛出错误,例如'length' in 'home'将抛出错误,但'length' in new String('home')不会)
const yoshi = { skulk: true };
const hattori = { sneak: true };
const kuma = { creep: true };
if ("skulk" in yoshi)
console.log("Yoshi can skulk");
if (!("sneak" in yoshi))
console.log("Yoshi cannot sneak");
if (!("creep" in yoshi))
console.log("Yoshi cannot creep");
Object.setPrototypeOf(yoshi, hattori);
if ("sneak" in yoshi)
console.log("Yoshi can now sneak");
if (!("creep" in hattori))
console.log("Hattori cannot creep");
Object.setPrototypeOf(hattori, kuma);
if ("creep" in hattori)
console.log("Hattori can now creep");
if ("creep" in yoshi)
console.log("Yoshi can also creep");
// https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/in
注意:有人可能会尝试使用 typeof 和 [ ] 属性访问器,如下所示的代码,但这种方法并不总是有效...
var loan = { amount: 150 };
loan.installment = undefined;
if("installment" in loan) // correct
{
// will execute
}
if(typeof loan["installment"] !== "undefined") // incorrect
{
// will not execute
}
检查对象上是否存在属性的更安全方法是使用空对象或对象原型来调用hasOwnProperty()
var foo = {
hasOwnProperty: function() {
return false;
},
bar: 'Here be dragons'
};
foo.hasOwnProperty('bar'); // always returns false
// Use another Object's hasOwnProperty and call it with 'this' set to foo
({}).hasOwnProperty.call(foo, 'bar'); // true
// It's also possible to use the hasOwnProperty property from the Object
// prototype for this purpose
Object.prototype.hasOwnProperty.call(foo, 'bar'); // true
hasOwnProperty
,那么任何类似于这样的防护措施都无法使你的代码安全可靠。 - meustrus有更简单的解决方案,我没有看到对你实际问题的答案:
"它正在寻找 myObj.myProp,但我希望它检查 myObj.prop"
true
),请使用in
运算符。或者,结合nullish coalescing运算符??以避免抛出错误。var nothing = undefined;
var obj = {prop:"hello world"}
var myProp = "prop";
consolelog( 1,()=> obj.myProp); // obj does not have a "myProp"
consolelog( 2,()=> obj[myProp]); // brackets works
consolelog( 3,()=> nothing[myProp]); // throws if not an object
consolelog( 4,()=> obj?.[myProp]); // optional chaining very nice ⭐️⭐️⭐️⭐️⭐️
consolelog( 5,()=> nothing?.[myProp]); // optional chaining avoids throwing
consolelog( 6,()=> nothing?.[nothing]); // even here it is error-safe
consolelog( 7,()=> !!obj?.[myProp]); // double-not yields true
consolelog( 8,()=> !!nothing?.[myProp]); // false because undefined
consolelog( 9,()=> myProp in obj); // in operator works
consolelog(10,()=> myProp in nothing); // throws if not an object
consolelog(11,()=> myProp in (nothing ?? {})); // safe from throwing
consolelog(12,()=> myProp in {prop:undefined}); // true (prop key exists even though its value undefined)
// beware of 'hasOwnProperty' pitfalls
// it can't detect inherited properties and 'hasOwnProperty' is itself inherited
// also comparatively verbose
consolelog(13,()=> obj.hasOwnProperty("hasOwnProperty")); // DANGER: it yields false
consolelog(14,()=> nothing.hasOwnProperty("hasOwnProperty")); // throws when undefined
obj.hasOwnProperty = ()=>true; // someone could overwrite it
consolelog(15,()=> obj.hasOwnProperty(nothing)); // DANGER: the foolish overwrite will now always return true
consolelog(16,()=> Object.prototype.hasOwnProperty.call(obj,"hasOwnProperty")); // explain?!
consolelog(17,()=> Object.hasOwn(obj,"hasOwnProperty")); // explain?!
function consolelog(num,myTest){
try{
console.log(num,myTest());
}
catch(e){
console.log(num,'throws',e.message);
}
}
hasOwnProperty()
方法以及in
运算符。使用新的Object.hasOwn
方法是另一种选择,其意图是替代Object.hasOwnProperty
方法。
该静态方法返回true,如果指定的对象具有指定属性作为其自己的属性,否则返回false,如果该属性是继承的或者在该对象上不存在。
请注意,在生产环境中使用此方法之前,请仔细检查浏览器兼容性表,因为它仍被视为实验性技术,并且尚未得到所有浏览器的完全支持(即将到来)。
var myObj = {};
myObj.myProp = "exists";
if (Object.hasOwn(myObj, 'myProp')){
alert("yes, i have that property");
}
了解更多关于Object.hasOwn
的信息 - https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwn
Object.hasOwn
的浏览器兼容性 - https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwn#browser_compatibility
检查对象属性是否存在的几种方法。
const dog = { name: "Spot" }
if (dog.name) console.log("Yay 1"); // Prints.
if (dog.sex) console.log("Yay 2"); // Doesn't print.
if ("name" in dog) console.log("Yay 3"); // Prints.
if ("sex" in dog) console.log("Yay 4"); // Doesn't print.
if (dog.hasOwnProperty("name")) console.log("Yay 5"); // Prints.
if (dog.hasOwnProperty("sex")) console.log("Yay 6"); // Doesn't print, but prints undefined.
对我来说工作正常。
if (typeof receviedData?.d?.heartbeat_interval != "undefined") {
}
hasOwnProperty
方法被覆盖了,你可以依靠Object.prototype.hasOwnProperty.call(object, property)
。」 - HumanInDisguise