source

속성 이름을 가진 변수가 있는 개체 속성이 있는지 확인하는 방법

bestscript 2022. 11. 13. 19:36

속성 이름을 가진 변수가 있는 개체 속성이 있는지 확인하는 방법

해당 속성명을 보유하는 변수를 가진 객체 속성이 존재하는지 확인 중입니다.

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

operator에서 를 사용하는 방법도 있습니다만, 여기에도 견적이 필요합니다.

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

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

여러분의 협조와 평가문 폐지를 추진해 주셔서 감사합니다.변수는 점 표기가 아닌 대괄호로 묶어야 합니다.이것은 동작하고, 깨끗하고, 적절한 코드입니다.

각각 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.protype.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

상속된 속성을 소견에 포함하려면 in 연산자를 사용합니다(단, 오브젝트를 in의 오른쪽에 배치해야 합니다).예를 들어 'home'의 'length'는 오류를 발생시키지만 새로운 String('home')의 'length'는 오류를 발생시키지 않습니다).

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

주의: Type of 및 [ ]속성 접근자를 다음 코드로 사용하고 싶은 경우가 있습니다.이 코드는 항상 기능하지 않습니다.

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

MDN Web Docs로부터의 레퍼런스 - Object.protype.hasOwnProperty()

훨씬 더 간단한 솔루션이 있지만 실제 질문에 대한 답을 찾을 수 없습니다.

"myObj.myProp를 찾고 있는데 myObj.prop을 확인하고 싶다."

  1. 변수에서 속성 값을 얻으려면 대괄호 표기법을 사용합니다.
  2. 해당 속성의 진부한 값을 테스트하려면 선택적 체인을 사용합니다.
  3. 부울을 반환하려면 double-not / bang-bang / (!)을 사용합니다.
  4. 개체가 있고 속성 존재 여부만 확인하는 경우 연산자를 사용합니다(true프로펠러 값이 정의되지 않은 경우에도).아니면 nullish coalesing 연산자와 결합할 수 있습니까?에러가 발생하는 것을 방지합니다.

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

function consolelog(num,myTest){
    try{
    console.log(num,myTest());
    }
    catch(e){
    console.log(num,'throws',e.message);
    }
}

하시면 됩니다.hasOwnProperty()만 아니라in환입니니다다

오브젝트 속성이 존재하는지 여부를 확인하는 방법에는 몇 가지 방법이 있습니다.

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.

" " " " 를 합니다.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/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwn

Object.hasOwn브라우저 호환성 - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwn#browser_compatibility

에서는요, 제가 못 !!진실성 체크

if (!!myObj.myProp) //Do something

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