속성 이름을 가진 변수에 객체 속성이 있는지 확인하는 방법은 무엇입니까?


680

속성 이름이있는 변수가있는 객체 속성이 있는지 확인하고 있습니다.

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


2
아마도 유용 할 것 : NCZOnline의 Pablo Cabrera의 코멘트에서 : " hasOwnProperty메소드를 덮어 쓰면에 의존 할 수 있습니다 Object.prototype.hasOwnProperty.call(object, property)."
— HumanInDisguise

10
이다 stackoverflow.com/questions/4244896/...는 이 질문의 중복? 방법 것입니다? '존재 확인'과 '액세스 가치'는 다른 것입니까? 내가 틀렸다면 저를 바로 잡으십시오 ....
— adnan2nd

이것은 중복되지 않습니다.
— Jeff Clayton

답변:


1308
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')그렇지 않습니다.


23
hasOwnProperty()myObj[myProp]값 myProp이 0 인 경우에도 작동하므로 다른 답변 보다 낫습니다.
— Matt R

9
"in"연산자는 문자열에서 작동하지 않습니다. 예를 들어 'qqq'의 'length'는 예외를 생성합니다. 따라서 범용 검사를 원하면 hasOwnProperty를 사용해야합니다.
— Jacob

1
@Jacob 'in'연산자가 문자열과 함께 작동하지 않는다는 말의 의미는 무엇입니까? "in" '연산자를 사용하면 왼쪽 표현식은 문자열 또는 문자열로 변환 할 수있는 값이어야합니다. 예, 'qqq'에는 '길이'를 쓸 수 없지만 'qqq'.hasOwnProperty ('length ')도 쓸 수 없습니다
— Wachburn

2
@Wachburn은 : 'qqq'.hasOwnProperty('length')있다 true, 당신은 할 수 있습니다.
— 로켓 Hazmat

1
@ gaurav5430 내가 말하는 myProp것은 0이면 if 문은 다음과 같이 보일 것 if (myObj[0])입니다.myObj 속성 은 ~로 평가된다는 것 true입니다. 그리고 myObj[0]당신이 찾고있는 재산이 아닐 수도 있습니다.
— Matt R

51

hasOwnProperty 를 사용할 수 있지만 이 방법을 사용할 때 참조를 기반으로 따옴표 가 필요 합니다 .

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

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

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

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

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


6
그것이 구현되는 방식 이 아닙니다hasOwnProperty() .
— canon

7
이것은 올바르지 않습니다. myProp 이름을 따옴표로 묶으면 더 이상 myProp의 값을 참조하지 않고 'myProp'의 새 String ()을 선언하고 myObj에 'myProp'의 해당 속성이 없습니다.
— TriumphST

1
TriumpST : 위에서 링크 된 MDN의 "prop-속성 이름 또는 배열 인덱스를 나타내는 문자열 또는 기호 (기호가 아닌 문자열은 문자열로 강제 변환 됨)"
— 벤 Creasy

맞습니다. 변수를 사용하고 싶지 않지만 특정 'myProp'이있는 경우 따옴표가 필요합니다.
— Katinka Hesselink

@KatinkaHesselink : 댓글이 잘못되었습니다. 문제는 "속성 이름을 가진 변수에 객체 속성이 있는지 확인하는 방법"이었습니다.
— Herbert Van-Vliet

26

모든 사람의 도움과 평가 진술을 없애기 위해 노력해 주셔서 감사합니다. 변수는 점 표기법이 아닌 괄호 안에 있어야합니다. 이것은 작동하고 깨끗하고 적절한 코드입니다.

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

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

이것은 나에게 문제처럼 보인다. 만약 tData.tonicdata[appChoice]일치하는 속성 / 인덱스가없는 값의 결과 underI,이는가 발생합니다 TypeError슬로우합니다.
— Ynot

초기 게시물에 대한 의도에도 불구하고 실제로이 답변을 제공 한 것과 다른 질문을했습니다. 속성이 있는지 확인하고 싶었지만 액세스 방법에 대해서는 언급하지 않았습니다. 이 답변은 실제 질문과 관련이 없습니다.
— Forage

19

자신의 재산 :

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

결과에 상속 된 속성을 포함하려면 in 연산자를 사용하십시오 (그러나 'in'의 오른쪽에 객체를 배치해야합니다. 기본 값은 오류를 발생시킵니다. 예를 들어 'home'의 'length'는 오류를 throw하지만 '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

참고 : 항상 작동하지 않는 다음 코드로 typeof 및 [] 속성 접근자를 사용하려는 유혹이있을 수 있습니다 ...

var loan = { amount: 150 };

loan.installment = undefined;

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

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

13

객체에 속성이 존재하는지 확인하는 훨씬 안전한 방법은 빈 객체 또는 객체 프로토 타입을 사용하여 호출하는 것입니다 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 웹 문서 에서 참조 -Object.prototype.hasOwnProperty ()


4
override와 같은 악의적 인 일을 할 수있는 JavaScript를 통합하는 경우 이와 같은 hasOwnProperty가드를 사용하지 않으면 코드가 안전하거나 안전합니다.
— meustrus

@meustrus 나는 당신이 어디에서 왔는지 알고 있지만, 비즈니스 관점에서 경험이 부족한 개발자 가이 속성 이름을 사용한다는 것은 매우 가능성이 높습니다.
— skmasq

당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.