JavaScript에서 객체에 키가 있는지 확인하는 5가지 방법
17720 단어 webdevcodenewbiebeginnersjavascript
"in" 연산자 사용
in 연산자는 지정된 속성이 지정된 객체 또는 해당 프로토타입 체인에 있는 경우 true를 반환하고, 그렇지 않으면 false를 반환합니다.const app = { name: 'Instagram', type: 'Social Media' };
console.log('name' in app); // true
console.log('release_date' in app); // false
Reflect.has() 메서드 사용
Reflect은 JavaScript 작업을 위한 몇 가지 유틸리티 메서드를 제공하는 내장 개체입니다. 이 개체의
has() 메서드는 지정된 속성이 지정된 개체 또는 해당 프로토타입 체인에 있는 경우 true를 반환하고, 그렇지 않으면 false를 반환합니다. 구문은 다음과 같습니다.Reflect.has(targetObject, propertyKey);
하나의 예에서 사용합시다.
const app = { name: 'Instagram', type: 'Social Media' };
console.log(Reflect.has(app, 'name')); // true
console.log(Reflect.has(app, 'release_date')); // false
hasOwnProperty() 메서드 사용
이 메서드는 개체 프로토타입에 있습니다. 따라서
Object.create(null) 로 생성되지 않은 객체는 이 메서드에 액세스할 수 있습니다. 이 메서드는 지정된 속성이 객체에 있는 경우(상속되지 않음) true를 반환하고 그렇지 않은 경우 false를 반환합니다.const app = { name: 'Instagram', type: 'Social Media' };
console.log(app.hasOwnProperty('type')); // true
console.log(app.hasOwnProperty('founder_name')); // false
속성에 액세스하고 "정의되지 않음"과 비교하여
객체에 존재하지 않는 속성에 액세스하면
undefined 를 반환합니다. 이렇게 하면 속성에 액세스하고 해당 값을 undefined와 비교하여 존재 여부를 알 수 있습니다.const app = { name: 'Instagram', type: 'Social Media' };
console.log(app['name'] === undefined); // false
console.log(app['founder_name'] === undefined); // true
// or simply use an if block without comparing to undefined
if (app['founder_name']) {
// do your work
}
객체에 속성이 존재하고 값이
undefined 인 경우 이 접근 방식으로는 속성의 존재를 확인할 수 없습니다.const auth = { token: undefined };
console.log(auth['token'] === undefined); // true
console.log(auth['timestamp'] === undefined); // true
Object.hasOwn() 메서드(ES2022 업데이트)
이 메서드는 지정된 속성이 객체에 있는 경우(상속되지 않음)
true를 반환하고 그렇지 않은 경우 false를 반환합니다.const app = { name: 'Instagram', type: 'Social Media' };
console.log(Object.hasOwn(app, 'type')); // true
console.log(Object.hasOwn(app, 'founder_name')); // false
hasOwnProperty() 및 hasOwn() 방법 외에 다른 세 가지 방법은 상속된 속성의 경우 잘 작동합니다. 그 한 예를 보자.function square(side) {
this.side = side;
}
square.prototype.getArea = function () {
return Math.pow(this.side, 2);
}
const sq = new square(5);
console.log(sq); // { side: 5 };
console.log(sq.getArea()); // 25
/*
Here "side" will be part of own object whereas
"getArea" will be inherited through prototype chain.
*/
// checking with 'in'
console.log('side' in sq); // true
console.log('getArea' in sq); // true
// checking with 'Reflect.has()'
console.log(Reflect.has(sq, 'side')); // true
console.log(Reflect.has(sq, 'getArea')); // true
// checking with 'hasOwnProperty()'
console.log(sq.hasOwnProperty('side')); // true
console.log(sq.hasOwnProperty('getArea')); // false
// comparing with 'undefined'
console.log(sq['side'] !== undefined); // true
console.log(sq['getArea'] !== undefined); // true
// checking with 'hasOwn()'
console.log(Object.hasOwn(sq, 'side')); // true
console.log(Object.hasOwn(sq, 'getArea')); // false
결론
처음 두 가지 접근 방식(
in 연산자 및 Reflect.has() 방법)이 더 두드러지는 반면 다른 세 가지 접근 방식에는 몇 가지 제한 사항이 있습니다.hasOwnProperty() 및 hasOwn() 메서드는 상속된 속성이 아닌 객체 자체 속성에 대해서만 작동합니다. hasOwnProperty() 방법은 Object.create(null)로 만든 객체에 사용할 수 없습니다. undefined와 비교"접근 방식은 지정된 속성이 존재하지만 값이 undefined인 경우가 아니면 제대로 작동합니다. 당신은 또한 좋아할 수 있습니다
시간 내주셔서 감사합니다 ❤️
jscurious.com에서 웹 개발에 대한 내 글을 더 찾아보십시오.
Reference
이 문제에 관하여(JavaScript에서 객체에 키가 있는지 확인하는 5가지 방법), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/amitavmishra99/5-ways-to-check-if-a-key-exists-in-an-object-in-javascript-22e9텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)