답변:
다음과 같이 객체의 속성을 반복 할 수 있습니다.
for(var prop in ad) {
if (ad.hasOwnProperty(prop)) {
// handle prop as required
}
}
hasOwnProperty()객체가 지정된 속성을 직접 속성으로 가지고 있고 객체의 프로토 타입 체인에서 상속되지 않는지 여부를 판별 하려면 메소드 를 사용하는 것이 중요합니다 .
주석에서 : 해당 코드를 함수에 넣고 주석 이있는 부분에 도달하자마자 false를 반환하도록 할 수 있습니다
성능 테스트
Object.keys것이 가장 쉬운 방법 이라고 생각합니다 . var a = [1,2,3];a.something=4;console.log(Object.keys(a))이미 ECMA 5에 포함되어 있으므로 안전하게 사용할 수 있습니다. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
Object.defineProperty(obj, 'foo', {enumerable:false, value:'foo'}).
내장 Object.keys메소드를 사용하여 객체의 키 목록을 가져 와서 길이를 테스트 할 수 있습니다.
var x = {};
// some code where value of x changes and than you want to check whether it is null or some object with values
if(Object.keys(x).length > 0){
// Your code here if x has some properties
}
var str = "MyString"; Object.keys(str);하면 콘솔은 각 문자에 대해 0에서 7까지 8 개의 키를 출력합니다. 아니면 여전히 답을 이해하지 못합니까?
간단한 기능을 만드는 것은 어떻습니까?
function isEmptyObject(obj) {
for(var prop in obj) {
if (Object.prototype.hasOwnProperty.call(obj, prop)) {
return false;
}
}
return true;
}
isEmptyObject({}); // true
isEmptyObject({foo:'bar'}); // false
에 hasOwnProperty직접 호출 하는 메소드 Object.prototype는 안전성을 조금만 높이는 것입니다 . 일반 obj.hasOwnProperty(...)호출을 사용하여 다음을 상상하십시오 .
isEmptyObject({hasOwnProperty:'boom'}); // false
주 : (미래에 대한) 위의 방법은에 의존 for...in문이 문은 반복 처리 열거 프로그래머가 아닌 열거 속성을 만들 수있는 방법이없는 현재 가장 널리 구현 인 ECMAScript 표준 (제 3 판)에서 속성을 .
그러나 이제 ECMAScript 5th Edition 에서 변경되었으며 열거 가능하지 않거나 쓰기 가능하지 않거나 삭제할 수없는 속성을 만들 수 있으므로 위의 방법 이 실패 할 수 있습니다 . 예 :
var obj = {};
Object.defineProperty(obj, 'test', { value: 'testVal',
enumerable: false,
writable: true,
configurable: true
});
isEmptyObject(obj); // true, wrong!!
obj.hasOwnProperty('test'); // true, the property exist!!
이 문제에 대한 ECMAScript 5 솔루션은 다음과 같습니다.
function isEmptyObject(obj) {
return Object.getOwnPropertyNames(obj).length === 0;
}
이 Object.getOwnPropertyNames메소드는 모든Array 이름을 포함 하는를 반환 합니다 자신의 속성 오브젝트의 열거 여부는 ,이 방법은 크롬 5 베타와 웹킷 박 빌드 최근에 이미, 브라우저 벤더에 의해 지금 시행되고있다.
Object.defineProperty 해당 브라우저 및 최신 Firefox 3.7 Alpha 릴리스에서도 사용할 수 있습니다.
hasOwnProperty속성을 재정의하면 함수가 충돌 할 수 있습니다 ... 나는 약간 편집증 적 인 것을 알고 있지만 때로는 어떤 환경에서 코드가 사용 될지 알지 못하지만 당신은 어떤 방법을 사용하고 싶은지 알고 있습니다.
Object.prototype의해 열거되지 않는 버그가 있습니다 for...in. 따라서 isEmptyObject({toString:1})실패합니다. 이것은 당신이 할 수없는 불행한 이유 중 하나입니다 꽤 사용하는 Object범용 매핑한다.
으로 jQuery를 사용하면 사용할 수 있습니다 :
$.isEmptyObject(obj); // Returns: Boolean
jQuery 1.4부터이 메소드는 객체 자체의 속성과 프로토 타입에서 상속 된 속성 (hasOwnProperty를 사용하지 않음)을 모두 확인합니다.
로 인 ECMAScript 5 판 현대적인 브라우저 (IE9 +, FF4 +, Chrome5 +, Opera12 +, Safari5 +) 당신은 내장 사용할 수 있습니다 Object.keys의 방법 :
var obj = { blah: 1 };
var isEmpty = !Object.keys(obj).length;
또는 평범한 오래된 JavaScript :
var isEmpty = function(obj) {
for(var p in obj){
return false;
}
return true;
};
최신 브라우저 (및 node.js)는 객체 리터럴에 모든 키가있는 배열을 반환하는 Object.keys ()를 지원하므로 다음을 수행 할 수 있습니다.
var ad = {};
Object.keys(ad).length;//this will be 0 in this case
브라우저 지원 : Firefox 4, Chrome 5, Internet Explorer 9, Opera 12, Safari 5
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
underscore.js를 사용하는 경우 _.isEmpty 함수를 사용할 수 있습니다 .
var obj = {};
var emptyObject = _.isEmpty(obj);
_.isEmpty([]) // true 먼저 확인하십시오 : stackoverflow.com/a/22482737/1922747
lodash를 기꺼이 사용 하려는 경우이some 방법을 사용할 수 있습니다 .
_.some(obj) // returns true or false
이 작은 jsbin 예제를 참조하십시오
_.some([1, 2]) // true 먼저 확인하십시오 : stackoverflow.com/a/13356338/1922747
for (var hasProperties in ad) break;
if (hasProperties)
... // ad has properties
안전해야하고 객체 프로토 타입을 확인해야하는 경우 (이것은 특정 라이브러리에 의해 추가되며 기본적으로 추가되지 않음) :
var hasProperties = false;
for (var x in ad) {
if (ad.hasOwnProperty(x)) {
hasProperties = true;
break;
}
}
if (hasProperties)
... // ad has properties
for(var memberName in ad)
{
//Member Name: memberName
//Member Value: ad[memberName]
}
멤버는 멤버 속성, 멤버 변수를 의미합니다.> _>
위의 코드는 toString을 포함한 모든 것을 반환합니다. 객체의 프로토 타입이 확장되었는지 확인하려는 경우 :
var dummyObj = {};
for(var memberName in ad)
{
if(typeof(dummyObj[memberName]) == typeof(ad[memberName])) continue; //note A
//Member Name: memberName
//Member Value: ad[memberName]
}
참고 A : 더미 객체의 멤버가 테스트 객체의 멤버와 동일한 유형인지 확인합니다. 그것이 확장이라면, 더미 객체의 멤버 타입은 "정의되지 않아야한다"
var hasAnyProps = false; for (var key in obj) { hasAnyProps = true; break; }
// as of this line hasAnyProps will show Boolean whether or not any iterable props exist
단순, 모든 브라우저에서 작동하고, 비록 기술적으로는 않는 개체에 대한 모든 키에 대한 루프의 NOT 그들 모두를 통해 루프를 ... 중 하나가 0이고 루프가 실행되지 않거나 일부가이며 최초의 후 휴식 하나 (우리가 확인하는 모든 것이 있다면 ... 계속 왜 그렇습니까?)
오브젝트가 사용자 정의 오브젝트인지 확인한 경우 UDO가 비어 있는지 판별하는 가장 쉬운 방법은 다음 코드입니다.
isEmpty=
/*b.b Troy III p.a.e*/
function(x,p){for(p in x)return!1;return!0};
이 방법은 본질적으로 연역적 인 방법이지만 가장 빠르며 가장 빠릅니다.
a={};
isEmpty(a) >> true
a.b=1
isEmpty(a) >> false
ps :! 브라우저 정의 객체에서는 사용하지 마십시오.
다음을 사용할 수 있습니다.
더블 뱅 !! 부동산 조회
var a = !![]; // true
var a = !!null; // false
hasOwnProperty 이것은 내가 사용했던 것입니다.
var myObject = {
name: 'John',
address: null
};
if (myObject.hasOwnProperty('address')) { // true
// do something if it exists.
}
그러나 JavaScript는 메소드 이름을 보호하지 않기로 결정했기 때문에 변경 될 수 있습니다.
var myObject = {
hasOwnProperty: 'I will populate it myself!'
};
myObject의 prop
var myObject = {
name: 'John',
address: null,
developer: false
};
'developer' in myObject; // true, remember it's looking for exists, not value.
유형
if (typeof myObject.name !== 'undefined') {
// do something
}
그러나 null을 확인하지 않습니다.
이것이 최선의 방법이라고 생각합니다.
운영자
var myObject = {
name: 'John',
address: null
};
if('name' in myObject) {
console.log("Name exists in myObject");
}else{
console.log("Name does not exist in myObject");
}
결과:
myObject에 이름이 있습니다
다음은 in 연산자에 대해 자세히 설명하는 링크입니다 . 객체 속성이 존재하는지 확인
ES6 기능
/**
* Returns true if an object is empty.
* @param {*} obj the object to test
* @return {boolean} returns true if object is empty, otherwise returns false
*/
const pureObjectIsEmpty = obj => obj && obj.constructor === Object && Object.keys(obj).length === 0
예 :
let obj = "this is an object with String constructor"
console.log(pureObjectIsEmpty(obj)) // empty? true
obj = {}
console.log(pureObjectIsEmpty(obj)) // empty? true
obj = []
console.log(pureObjectIsEmpty(obj)) // empty? true
obj = [{prop:"value"}]
console.log(pureObjectIsEmpty(obj)) // empty? true
obj = {prop:"value"}
console.log(pureObjectIsEmpty(obj)) // empty? false
이건 어때요?
var obj = {},
var isEmpty = !obj;
var hasContent = !!obj