if(개체의 키) 또는 if(object.hasOwnProperty(키))
다음 두 문장은 동일한 출력을 생성합니까?다른 방법보다 한 가지 방법을 더 선호할 이유가 있나요?
if (key in object)
if (object.hasOwnProperty(key))
조심하세요. 같은 결과가 나오지 않을 거예요.
in
반환됩니다.true
key
시제품 체인의 어딘가에서 발견됩니다.Object.hasOwnProperty
수 있듯이)는만 한다.true
key
는, 그 오브젝트에서 직접 사용할 수 있습니다(그 오브젝트의 「속성」).
다른 예를 들어 설명하겠습니다.두 가지 속성을 가진 다음 개체가 있다고 가정합니다.
function TestObj(){
this.name = 'Dragon';
}
TestObj.prototype.gender = 'male';
TestObj 인스턴스를 만듭니다.
var o = new TestObj();
오브젝트 인스턴스를 조사합니다.
console.log(o.hasOwnProperty('name')); // true
console.log('name' in o); // true
console.log(o.hasOwnProperty('gender')); // false
console.log('gender' in o); // true
결론:
in 연산자는 속성을 객체가 직접 또는 프로토타입에서 액세스할 수 있는 경우 항상 true를 반환합니다.
hasOwnProperty()가 true를 반환하는 것은 속성이 인스턴스에 존재하지만 프로토타입에는 존재하지 않는 경우뿐입니다.
프로토타입에 어떤 속성이 존재하는지 확인하려면 논리적으로 다음과 같이 말할 수 있습니다.
console.log(('name' in o) && !o.hasOwnProperty('name')); //false
console.log(('gender' in o) && !o.hasOwnProperty('gender')); //true - it's in prototype
마지막으로:
그래서 이 두 가지 조건에 대해서...
if (key in object)
if (object.hasOwnProperty(key))
...같은 결과를 낳는다, 답은 명백하다, 상황에 따라 다르다.
in
하지만, properties속만 、 will 、 will 、 will 、 will 、 will 、 will 、 will 、 will will will will will will will will will will 。hasOwnProperty
.
「」입니다.hasOwnProperty()
이 경우 프로토타입을 볼 수 없습니다.in
프로토타입을 살펴봅니다.
O'Reilly High Performance Javascript에서 인용:
hasOwnProperty() 메서드를 사용하여 멤버 이름을 전달함으로써 객체에 지정된 이름의 인스턴스 멤버가 있는지 여부를 판별할 수 있습니다.개체가 지정된 이름의 속성에 액세스할 수 있는지 여부를 확인하려면 in 연산자를 사용합니다.예를 들어 다음과 같습니다.
var book = {
title: "High Performance JavaScript",
publisher: "Yahoo! Press"
};
alert(book.hasOwnProperty("title")); //true
alert(book.hasOwnProperty("toString")); //false
alert("title" in book); //true
alert("toString" in book); //true
이 코드에서는 제목이 오브젝트인스턴스이기 때문에 hasOwnProperty()는 "title"이 전달되면 true를 반환하고, "toString"이 인스턴스에 존재하지 않기 때문에 메서드는 false를 반환합니다.각 속성 이름을 in 연산자와 함께 사용하면 인스턴스와 프로토타입을 검색하기 때문에 결과가 모두 참입니다.
정말 좋은 답을 얻으셨네요오브젝트를 반복하는 동안 "HasOwnProperty"를 체크할 필요가 없어지는 것을 제안하고 싶습니다.
오브젝트를 작성할 때 보통 다음과 같은 방법으로 작성됩니다.
const someMap = {}
// equivalent to: Object.create(Object.prototype)
// someMap.constructor will yield -> function Object() { [native code] }
이제 "someMap"을 통해 반복하려면 다음과 같이 해야 합니다.
const key
for(key in someMap ){
if (someMap.hasOwnProperty(key)) {
// Do something
}
}
상속된 속성에 대한 반복을 방지하기 위해 이 작업을 수행하고 있습니다.
"맵"으로만 사용되는 단순한 객체(예: 키와 값의 쌍)를 작성하려는 경우 다음과 같이 할 수 있습니다.
const newMap = Object.create(null);
// Now, newMap won't have prototype at all.
// newMap.constructor will yield -> undefined
따라서 이렇게 반복하는 것이 안전합니다.
for(key in cleanMap){
console.log(key + " -> " + newMap [key]);
// No need to add extra checks, as the object will always be clean
}
이 멋진 팁을 여기서 배웠어요.
다른 형식(호출된 형식)은 개체의 속성 이름(또는 키)을 열거합니다.반복할 때마다 객체의 다른 속성 이름 문자열이 변수에 할당됩니다.일반적으로 object.hasOwnProperty(변수)를 테스트하여 속성 이름이 실제 객체의 멤버인지 또는 프로토타입 체인으로 검색되었는지 확인해야 합니다.
for (myvar in obj) {
if (obj.hasOwnProperty(myvar)) { ... } }
(Crockford의 Javascript: 좋은 부분)
다른 답변에서도 알 수 있듯이hasOwnProperty
오브젝트 자신의 속성을 체크합니다.속성을 확인합니다.in
상속된 속성도 확인합니다.
새로운 방법 2021 -Object.hasOwn()
을 대신해서Object.hasOwnProperty()
Object.hasOwn()
를 대체하기 위한 것입니다.Object.hasOwnProperty()
새로운 방법을 사용할 수 있습니다(여기서 보시는 바와 같이 모든 브라우저에서 완전히 지원되는 것은 아닙니다.https://caniuse.com/?search=hasDown )
Object.hasOwn()
는 지정된 객체의 속성으로 지정된 속성이 있는 경우 true를 반환하는 스태틱메서드입니다.속성이 상속되거나 존재하지 않으면 메서드는 false를 반환합니다.
const person = { name: 'dan' };
console.log(Object.hasOwn(person, 'name'));// true
console.log(Object.hasOwn(person, 'age'));// false
const person2 = Object.create({gender: 'male'});
console.log(Object.hasOwn(person2, 'gender'));// false
이 방법을 사용하는 것이 좋습니다.Object.hasOwnProperty()
를 사용하여 작성한 오브젝트에도 사용할 수 있기 때문입니다.Object.create(null)
상속된 오브젝트를 덮어쓴 경우hasOwnProperty()
방법.전화하면 이런 문제를 해결할 수 있지만Object.prototype.hasOwnProperty()
외부 물체에 대해Object.hasOwn()
이러한 문제를 극복하는 것이 바람직합니다(아래 예 참조).
let person = {
hasOwnProperty: function() {
return false;
},
age: 35
};
if (Object.hasOwn(person, 'age')) {
console.log(person.age); // true - the remplementation of hasOwnProperty() did not affect the Object
}
let person = Object.create(null);
person.age = 35;
if (Object.hasOwn(person, 'age')) {
console.log(person.age); // true - works regardless of how the object was created
}
상세 정보Object.hasOwn
는, 다음의 URL 에 있습니다.https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwn
브라우저 호환성 - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwn#browser_compatibility
첫 번째 버전은 더 짧습니다(특히 변수 이름이 변경되는 최소화된 코드).
a in b
대
b.hasOwnProperty(a)
어쨌든, @AndreMeinhold가 말한 것처럼, 반드시 같은 결과를 얻을 수 있는 것은 아닙니다.
언급URL : https://stackoverflow.com/questions/13632999/if-key-in-object-or-ifobject-hasownpropertykey
'programing' 카테고리의 다른 글
Custom Nova Tool에서 Laravel Nova 구성 요소를 사용하는 방법 (0) | 2022.09.04 |
---|---|
전체 파일을 읽으면 파일 핸들이 열린 상태로 유지됩니까? (0) | 2022.09.04 |
phpmyadmin은 docker-param을 사용하여 mariadb에 접속할 수 없습니다.패킷의 순서가 잘못되어 있다 (0) | 2022.09.04 |
Node.js에서 파일을 자동 새로고침하는 방법 (0) | 2022.09.04 |
if(a - b < 0)와 if(a < b)의 차이 (0) | 2022.09.03 |