如何使用包含属性名称的变量检查对象属性是否存在? [英] How to check if object property exists with a variable holding the property name?

查看:170
本文介绍了如何使用包含属性名称的变量检查对象属性是否存在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在检查是否存在一个带有保存有问题的属性名称的变量的对象属性。

I am checking for the existence of an object property with a variable holding the property name in question.

var myObj;
myObj.prop = "exists";
var myProp = "p"+"r"+"o"+"p";

if(myObj.myProp){
    alert("yes, i have that property");
};

这是 undefined 因为它正在寻找 myObj.myProp 但我希望它检查 myObj.prop

This is undefined because it's looking for myObj.myProp but I want it to check for 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");
}

这篇关于如何使用包含属性名称的变量检查对象属性是否存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆