빈 JavaScript 객체 시험 어떻게 합니까?

때때로 AJAX 요청을 한 후, 빈 객체에는 복귀하십시오 내 응용 프로그램은 다음과 같습니다.

var a = {};

39 의 경우 that& 여부를 확인할 수 있습니까?

질문에 대한 의견 (1)
해결책

[ECMA 7+] [9]:

// because Object.entries(new Date()).length === 0;
// we have to do some additional check
Object.entries(obj).length === 0 && obj.constructor === Object

[ECMA 5+] [1]:

// because Object.keys(new Date()).length === 0;
// we have to do some additional check
Object.keys(obj).length === 0 && obj.constructor === Object

사전 ecma 5:

function isEmpty(obj) {
  for(var prop in obj) {
    if(obj.hasOwnProperty(prop)) {
      return false;
    }
  }

  return JSON.stringify(obj) === JSON.stringify({});
}

jQuery:

jQuery.isEmptyObject({}); // true

[로다시] [3]:

_.isEmpty({}); // true

[밑줄] [4]:

_.isEmpty({}); // true

Hoek.deepEqual({}, {}); // true

[에스티스] [6]

Ext.Object.isEmpty({}); // true

앙굴라이스 (버전 1)

angular.equals({}, {}); // true

[람다] [8]

R.isEmpty({}); // true

[1]: # Browser_compatibility https://developer.mozilla.org/en-us/docs/web/javascript/reference/global_objects/object/keys

[3]: https://lodash.com/docs # 이왕티 [4]: https://underscorejs.org/ # 이왕티

[6]: https://docs.sencha.com/extjs/6.0.2/modern/Ext.Object.html # 이왕티 방법

[8]: https://ramdajs.com/docs/ # 이왕티 [9]: # Browser_compatibility https://developer.mozilla.org/en-us/docs/web/javascript/reference/global_objects/object/entries

해설 (28)

39 의 there& 결코 간단한 방법으로 이. # 39, ll %s/dbase/ext_table. you& 반복할 속성을 통해 명시적으로:

function isEmpty(obj) {
    for(var prop in obj) {
        if(obj.hasOwnProperty(prop))
            return false;
    }

    return true;
}

만약 [ECMAScript 5 지원] (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys # Browser_compatibility) 를 사용할 수 있는 '로비치스키스 ()' 대신 사용할 수 있습니다.

function isEmpty(obj) {
    return Object.keys(obj).length === 0;
}
해설 (16)

Jquery 는 동일한 문제가 아니라 사용는 너희가운데 위해 사용할 수 있습니다. [제크리스즈mpt요비치] (http://api.jquery.com/jQuery.isEmptyObject/).

해설 (16)

이건 내 우선 솔루션:

var obj = {};
return Object.keys(obj).length; //returns 0 if empty or an integer > 0 if non-empty
해설 (5)

[언더스코엘가이스] [1] 사용할 수 있습니다.

_.isEmpty({}); // true

[1]: http://underscorejs.org/ # 이왕티

해설 (8)
if(Object.getOwnPropertyNames(obj).length === 0){
  //is empty
}

http://bencollier.net/2011/04/javascript-is-an-object-empty/ 참조

해설 (4)

제슨.스트린그리피 사용하여 어때? 사용할 수 있는 것은 거의 모든 최신 브라우저.

function isEmptyObject(obj){
    return JSON.stringify(obj) === '{}';
}
해설 (5)

오래된 질문 한 것이 아니라, 경식도 배정됩니다. Jquery 는 정말 좋은 아이디어 여부를 확인할 수 없는 경우 등 해결할 수 있는 유일한 목적은 객체인지 비어 있지 않습니다. 대신 그냥 깊이 있게 JQuery& # 39 의 코드, 그리고 답을 얻을 수 있습니다.

function isEmptyObject(obj) {
    var name;
    for (name in obj) {
        if (obj.hasOwnProperty(name)) {
            return false;
        }
    }
    return true;
}
해설 (2)

그냥 실행했음 salesforce. 상황은 비슷하다. # 39, 내가 보고 싶지 않다, 이를 사용하여 didn& 순결케 사용하여 Javascript 를 포함한다.

내가 한 것은 다음과 같은 조건, 그리고 나를 위해 사용한 통했다.

var obj = {};
if(JSON.stringify(obj) === '{}') { //This will check if the object is empty
   //Code here..
}

같지 않은 경우, 이: = {} & # 39, & # 39 제슨.스트린그리피 (목표) ','!

체크아웃하려고 이 [이스피들] [1]

해설 (7)

간단하게 아니했다고 오른길로 경우 최신 브라우저. '로비치스키스 트렌크스 (목표) = 0'

해설 (5)

개체 수를 확인할 수 있습니다 키:

if (Object.keys(a).length > 0) {
    // not empty
}
해설 (2)
  1. 그냥 해결하십시오. 서버 발령합니다 유지할 수 없는 특별한 성질) 의 경우, 일부 데이터?

예를 들면 다음과 같습니다.

var a = {}, 진정한 빈.

그런 다음 다시 체크인될 쉽게 너회의 아약스 콜백하는 코드입니다.

  1. 다른 방법을 살펴보자.

if (= &quot 앨토수르스 (), ({}) ") 그 후, a& # 39, & # 39 // 비워집니다

  • 편집할지 *: Json 라이브러리를 사용할 경우 (프리에벌린 그럼 제슨.j스) 및 테스트 결과 값을 구체화하십시오. () 함수를 제슨.렌코드 포지셔닝하여 비어 있다.
해설 (11)

로비치스키스 (목표) 를 사용하여 트렌크스 (위) 로 제안됩니다 ECMA 5+) 가 10 번 객체에는 느린 됩니다! 렉시한테서 있는 올드 스쿨 (for.in) 옵션.

크롬, 파이어폭스, 인터넷 익스플로러 9 에서 테스트되었습니다 노드입니다 볼 수 있는 대부분의 활용 및 됩니다.

    • (for.in). 가장 빠르게 사용할 수 있는 옵션을! *
      • 로비치스키스 (목표) 는 10 배로 객체에는 트렌크스 느린 됩니다 항상 최저속 - 제슨.스트린그리피 트렌크스 아닌 의외) (목표)
    • 오브ject.게타운프로페르티나미스 트렌크스 로비치스키스 (목표) (목표) 보다 훨씬 더 일부 시스템에서는 트렌크스 * 시간이 오래 걸릴 수 있습니다.

요컨대 성능 현명한 사용합니다.

function isEmpty(obj) { 
   for (var x in obj) { return false; }
   return true;
}

또는

function isEmpty(obj) {
   for (var x in obj) { if (obj.hasOwnProperty(x))  return false; }
   return true;
}

자세한 테스트 결과 및 테스트 코드를 dell. https://stackoverflow.com/questions/4994201/is-object-empty/34491287 # 34491287 지켜보리니

해설 (0)

39, ve i& 완료하십시오 확인하기 위해 만든 함수 객체 비워집니다.

정보기술 (it) 에서는 '로비치스키스' 에서 [ecmascript 5] [ecma 5] (es5) 기능을 경우 최상의 성능을 얻을 수 있습니다 (자세한 내용은 [호환성에서는 표] [ecma 5 호환성]) 및 대체 방법이 가장 호환적 외곽진입 종전의 엔진 (브라우저).

솔루션이므로

<! - 언어: 자바스크립트 - &gt.

/**
 * Returns true if specified object has no properties,
 * false otherwise.
 *
 * @param {object} object
 * @returns {boolean}
 */
function isObjectEmpty(object)
{
    if ('object' !== typeof object) {
        throw new Error('Object must be specified.');
    }

    if (null === object) {
        return true;
    }

    if ('undefined' !== Object.keys) {
        // Using ECMAScript 5 feature.
        return (0 === Object.keys(object).length);
    } else {
        // Using legacy compatibility mode.
        for (var key in object) {
            if (object.hasOwnProperty(key)) {
                return false;
            }
        }
        return true;
    }
}

39 의 here&, [사진을] [사진을] 이 코드.

39 의 및 here&, [이스피들] [이스피들] 와 데모 및 간단한 테스트를.

누군가 데 도움이 될 것이라고 기대한다. 건배!

[ecma 5]: http://en.wikipedia.org/wiki/ECMAScript # ECMAScript.2C_5th_Edition [ecma 5 호환성]: # 로비치스키스 http://kangax.github.io/compat-table/es5/

[사진을]: https://gist.github.com/slavafomin/c7ab7f7e45431748ad8c # 비어 있는 파일 객체에는 js

해설 (4)

지금 사용하고 있습니다.

function isObjectEmpty(object)
{
  var isEmpty = true;
  for(keys in object)
  {
     isEmpty = false;
     break; // exiting since we found that the object is not empty
  }
  return isEmpty;
}

예:

var myObject = {}; // Object is empty
var isEmpty  = isObjectEmpty(myObject); // will return true;

// populating the object
myObject = {"name":"John Smith","Address":"Kochi, Kerala"}; 

// check if the object is empty
isEmpty  = isObjectEmpty(myObject); // will return false;

from here

  • 업데이트 *

또는

jquery 구현 이렘프티오비치 사용할 수 있습니다.

function isEmptyObject ( obj ) {
        var name;
        for ( name in obj ) {
            return false;
        }
        return true;
    }
해설 (2)

다음 예제에서는 테스트하려면 javascript 객체여야 비워집니다 보여 경우 경우 빈 저희에게는힘과 고말은 주님으로부터그에게 İç 속성을 통해 it.

스크립트입니다 ES6 작동합니다.

<! - begin 스니핏: js 숨기십시오: 거짓값 콘솔: 진정한 바벨. &gt 거짓값 -;

const isEmpty = (obj) => {
    if (obj === null ||
        obj === undefined ||
        Array.isArray(obj) ||
        typeof obj !== 'object'
    ) {
        return true;
    }
    return Object.getOwnPropertyNames(obj).length === 0;
};
console.clear();
console.log('-----');
console.log(isEmpty(''));           // true
console.log(isEmpty(33));           // true
console.log(isEmpty([]));           // true
console.log(isEmpty({}));           // true
console.log(isEmpty({ length: 0, custom_property: [] })); // false
console.log('-----');
console.log(isEmpty('Hello'));      // true
console.log(isEmpty([1, 2, 3]));    // true
console.log(isEmpty({ test: 1 }));  // false
console.log(isEmpty({ length: 3, custom_property: [1, 2, 3] })); // false
console.log('-----');
console.log(isEmpty(new Date()));   // true
console.log(isEmpty(Infinity));     // true
console.log(isEmpty(null));         // true
console.log(isEmpty(undefined));    // true

끝 - &lt 스니핏 >;!

해설 (0)
function isEmpty(obj) {
  for(var i in obj) { return false; }
  return true;
}
해설 (1)

&gt. 오브ject.렌트리스 () 에 따라 ES2017 사양명세 해당 검사가 &gt. 간단한 사용 중인 최신 브라우저 -

Object.entries({}).length === 0
해설 (2)

jQuery 수 있는 특수 함수 () '이' 이렘프티오비치 사례:

jQuery.isEmptyObject({}) // true
jQuery.isEmptyObject({ foo: "bar" }) // false

대한 자세한 내용은 http://api.jquery.com/jQuery.isEmptyObject/

해설 (2)

비어 있는 모든 방법으로 키를 사용하여 모든 라이브러리보다는 후드 아래에 확인란 객체에는 확인할 수 없다. 그 이상한 방식으로 이해할 수 있게 할 수 있는 방법을 설명됨 넣어 here.

for(key in obj){
   //your work here.
 break;
}

ES5 에서 진화한 디스크입니다. diskid 간단히 말해, 이제 # 39 의 키 길이를 사용하는 로비치스키스 object& 확인할 수 있습니다 ',' 방법을 담당하는 # 39 의 너회의 로케이터로 it& 매개변수입니다:

if(Object.keys(obj).length > 0){
 //do your work here
}

[로다시] 또는 3 (합니다) 을 사용하는 경우.

 _.isEmpty(obj) //==true or false
해설 (1)