Nice programing

속성 이름을 포함하는 변수로 개체 속성이 있는지 확인하는 방법은 무엇입니까?

nicepro 2020. 10. 2. 23:19
반응형

속성 이름을 포함하는 변수로 개체 속성이 있는지 확인하는 방법은 무엇입니까?


문제의 속성 이름을 보유하는 변수가있는 개체 속성의 존재를 확인하고 있습니다.

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


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사실이지만 myObj.hasOwnProperty('constructor')그렇지 않습니다.


hasOwnProperty 를 사용할 수 있지만 참조를 기반 으로이 메서드를 사용할 때 따옴표필요 합니다 .

if (myObj.hasOwnProperty('myProp')) {
    // do something
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty

또 다른 방법은 in operator 를 사용 하는 것이지만 여기에도 따옴표 가 필요 합니다 .

if ('myProp' in myObj) {
    // do something
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in


모든 분들의 도움에 감사 드리며 eval 성명을 제거 해주시기 바랍니다. 변수는 점 표기법이 아니라 괄호 안에 있어야합니다. 이것은 작동하고 깨끗하고 적절한 코드입니다.

각각의 변수는 appChoice, underI, underObstr입니다.

if(typeof tData.tonicdata[appChoice][underI][underObstr] !== "undefined"){
    //enter code here
}

자신의 재산 :

var loan = { amount: 150 };
if(Object.prototype.hasOwnProperty.call(loan, "amount")) 
{ 
   //will execute
}

참고 : 사용자 정의 hasOwnProperty가 프로토 타입 체인에 정의 된 경우 (여기서는 그렇지 않음) 다음과 같이 Object.prototype.hasOwnProperty를 사용하는 것이 loan.hasOwnProperty (..)보다 낫습니다.

var foo = {
      hasOwnProperty: function() {
        return false;
      },
      bar: 'Here be dragons'
    };

// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty

To include inherited properties in the finding use the in operator: (but you must place an object at the right side of 'in', primitive values will throw error, e.g. 'length' in 'home' will throw error, but 'length' in new String('home') won't)

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/en-US/docs/Web/JavaScript/Reference/Operators/in

Note: One may be tempted to use typeof and [ ] property accessor as the following code which doesn't work always ...

var loan = { amount: 150 };

loan.installment = undefined;

if("installment" in loan) // correct
{
    // will execute
}

if(typeof loan["installment"] !== "undefined") // incorrect
{
    // will not execute
}

A much more secure way to check if property exists on the object is to use empty object or object prototype to call 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

Reference from MDN Web Docs - Object.prototype.hasOwnProperty()


You can use hasOwnProperty() as well as in operator.

참고URL : https://stackoverflow.com/questions/11040472/how-to-check-if-object-property-exists-with-a-variable-holding-the-property-name

반응형