source

빈 JavaScript 개체를 테스트하려면 어떻게 해야 합니까?

nicesource 2023. 7. 8. 10:58
반응형

빈 JavaScript 개체를 테스트하려면 어떻게 해야 합니까?

AJAX 요청 후 때때로 내 응용 프로그램이 다음과 같은 빈 개체를 반환할 수 있습니다.

var a = {};

해당 여부는 어떻게 확인할 수 있습니까?

에 …을 …의 …과 할 수 .Object.hasOwn(ECMA 2022+) 테스트를 통해 개체에 고유한 속성이 있는지 확인합니다.

function isEmpty(obj) {
  for (const prop in obj) {
    if (Object.hasOwn(obj, prop)) {
      return false;
    }
  }

  return true;
}

또한 구별이 필요한 경우{}속성이 빈 - 고한속없성예다는개른빈유사개다니합와체의체이유예▁from▁objects▁empty(▁-:다)Date다양한(불행히도 필요에 따라) 유형 검사를 수행할 수 있습니다.

function isEmptyObject(value) {
  if (value == null) {
    // null or undefined
    return false;
  }

  if (typeof value !== 'object') {
    // boolean, number, string, function, etc.
    return false;
  }

  const proto = Object.getPrototypeOf(value);

  // consider `Object.create(null)`, commonly used as a safe map
  // before `Map` support, an empty object as well as `{}`
  if (proto !== null && proto !== Object.prototype) {
    return false;
  }

  return isEmpty(value);
}

해보시오십과 비교해 .Object.prototype이 예와 마찬가지로 크로스오버 개체를 인식하지 못합니다.

를 사용하지 . Object.keys(obj).length모든 속성 이름을 포함하는 배열을 생성하여 해당 배열의 길이를 가져오기 때문에 O(N) 복잡성입니다.개체 위에서 반복하면 O(1)와 같은 목표를 달성합니다.

2022을 위해 ES 2022+와 ES 2022+는 JavaScript를 지원합니다.const는 대할수있니다습체로 할 수 있습니다.var그리고.Object.hasOwn와 함께Object.prototype.hasOwnProperty.call:

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

  return true
}

많은 인기 있는 라이브러리는 빈 개체를 확인하는 기능도 제공합니다.

jQuery:

jQuery.isEmptyObject({}); // true

로다쉬:

_.isEmpty({}); // true

밑줄:

_.isEmpty({}); // true

후크:

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

ExtJS:

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

AngularJS(버전 1):

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

람다:

R.isEmpty({}); // true

ECMA스크립트 5 지원을 사용할 수 있는 경우Object.keys():

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

ES3 이상의 경우 이를 위한 쉬운 방법이 없습니다.속성을 명시적으로 반복해야 합니다.

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

    return true;
}

동일한 문제가 있지만 jQuery를 사용하는 사용자는 jQuery.is EmptyObject를 사용할 수 있습니다.

성능

현재 2023.3.20 Chrome v109, Safari v15.2 및 Firefox v110에서 MacOs Monterey 12.1(M1, 16GB)에서 선택한 솔루션에 대한 테스트를 수행하고 있습니다.

결론들

  • 기솔션에 for-in은 모든 (A, L)에서.
  • 기솔션에 JSON.stringify .

enter image description here

세부 사항

해결책은 아래 스니펫에 나와 있습니다.컴퓨터에서 성능 테스트를 실행하려면 다음을 클릭합니다.

  • 개체에 대한 HERE
  • 개체 스위치 10개 필드에 대한 HERE
  • 필드가 100개인 개체의 경우 HERE

이 답변의 이전 버전에는 2020 - HERE의 테스트가 포함되어 있습니다.

답변 링크: A, B, C, D, E, F, G, H, I, J, K, L, M, N, OQ

var log = (s, f) => console.log(`${s} --> {}:${f({})}  {k:2}:${f({ k: 2 })}`);

function A(obj) {
  for (var i in obj) return false;
  return true;
}

function B(obj) {
  return JSON.stringify(obj) === "{}";
}

function C(obj) {
  return Object.keys(obj).length === 0;
}

function D(obj) {
  return Object.entries(obj).length === 0;
}

function E(obj) {
  return Object.getOwnPropertyNames(obj).length === 0;
}

function F(obj) {
  return Object.keys(obj).length === 0 && obj.constructor === Object;
}

function G(obj) {
  return typeof obj === "undefined" || !Object.keys(obj)[0];
}

function H(obj) {
  return Object.entries(obj).length === 0 && obj.constructor === Object;
}

function I(obj) {
  return Object.values(obj).every((val) => typeof val === "undefined");
}

function J(obj) {
  for (const key in obj) {
    if (hasOwnProperty.call(obj, key)) {
      return false;
    }
  }
  return true;
}

function K(obj) {
  var isEmpty = true;
  for (keys in obj) {
     isEmpty = false;
     break;
  }
  return isEmpty;
}

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

function M(obj) {
  if (obj === null || typeof obj !== 'object' ||
    Object.prototype.toString.call(obj) === '[object Array]') {
    return false
  } else {
    for (var prop in obj) {
      if (obj.hasOwnProperty(prop)) {
        return false
      }
    }
    return JSON.stringify(obj) === JSON.stringify({})
  }
}

function N(obj) {
  return (
    Object.getOwnPropertyNames(obj).length === 0 &&
    Object.getOwnPropertySymbols(obj).length === 0 &&
    Object.getPrototypeOf(obj) === Object.prototype
  );
}

function O(obj) {
  return !(Object.getOwnPropertyNames !== undefined
    ? Object.getOwnPropertyNames(obj).length !== 0
    : (function () {
        for (var key in obj) break;
        return key !== null && key !== undefined;
      })());
}

function P(obj) {
  return $.isEmptyObject(obj)
}

function Q(obj) {
  return _.isEmpty(obj);
}

log("A", A);
log("B", B);
log("C", C);
log("D", D);
log("E", E);
log("F", F);
log("G", G);
log("H", H);
log("I", I);
log("J", J);
log("K", K);
log("L", L);
log("M", M);
log("N", N);
log("O", O);
log("P", P);
log("Q", Q);
<script
  src="https://code.jquery.com/jquery-3.6.4.min.js"
  integrity="sha256-oP6HI9z1XaZNBrJURtCoUT5SUnxFr8s3BzRl+cbzUq8="
  crossorigin="anonymous"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.13.6/underscore-min.js" integrity="sha512-2V49R8ndaagCOnwmj8QnbT1Gz/rie17UouD9Re5WxbzRVUGoftCu5IuqqtAM9+UC3fwfHCSJR1hkzNQh/2wdtg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

enter image description here

언더스코어.js를 사용할 수 있습니다.

_.isEmpty({}); // true
if(Object.getOwnPropertyNames(obj).length === 0){
  //is empty
}

http://bencollier.net/2011/04/javascript-is-an-object-empty/ 을 참조하십시오.

JSON.stringify를 사용하는 것은 어떻습니까?그것은 거의 모든 최신 브라우저에서 사용할 수 있습니다.

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

최신 브라우저에 있는 경우 간단한 방법이 있습니다. Object.keys(obj).length === 0

오래된 질문이지만 문제가 있었습니다.개체가 비어 있지 않은지 확인하는 것이 유일한 목적이라면 JQuery를 포함하는 것은 좋은 생각이 아닙니다.대신 JQuery의 코드를 자세히 살펴보면 다음과 같은 답을 얻을 수 있습니다.

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

Object.keys(obj)를 사용합니다.길이(ECMA 5+의 경우 위에서 제안한 바와 같이)는 빈 개체의 경우 10배 느립니다! 이전 학교(...in) 옵션을 사용하십시오.

Node, Chrome, Firefox 및 IE 9에서 테스트한 결과 대부분의 사용 사례는 다음과 같습니다.

  • (...의 경우)가 가장 빠른 옵션입니다!
  • Object.keys(obj)입니다.빈 개체의 경우 길이가 10배 느림
  • JSON.stringify(obj).길이가 항상 가장 느림(놀랍지 않음)
  • Object.getOwnPropertyNames(obj)입니다.길이가 Object.keys(obj)보다 오래 걸립니다.일부 시스템에서는 길이가 훨씬 더 길어질 수 있습니다.

성능을 고려할 때 다음을 사용합니다.

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;
}

Is object is empty에서 자세한 테스트 결과 및 테스트 코드를 참조하십시오.

내 생각엔:

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

var a = {
  a: 1,
  b: 2
}
var b = {}

console.log(isEmpty(a)); // false
console.log(isEmpty(b)); // true

단지, 모든 브라우저가 구현되는 것은 아닌 것 같습니다.Object.keys()현재의.

이거 쓰고 있어요.

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;

여기서부터

갱신하다

OR

is EmptyObject의 jQuery 구현을 사용할 수 있습니다.

function isEmptyObject(obj) {
  var name;
  for (name in obj) {
    return false;
  }
  return true;
}
  1. 해결책일 뿐입니다.데이터가 없는 경우 서버에서 특별한 속성을 생성할 수 있습니까?

    예:

    var a = {empty:true};
    

    그러면 AJAX 콜백 코드에서 쉽게 확인할 수 있습니다.

  2. 다른 확인 방법:

    if (a.toSource() === "({})")  // then 'a' is empty
    

편집: JSON 라이브러리(예: JSON.js)를 사용하는 경우 JSON.encode() 함수를 사용하여 빈 값 문자열에 대해 결과를 테스트할 수 있습니다.

개체 사용.열쇠들.

Object.keys는 개체의 속성 이름을 포함하는 배열을 반환합니다.배열의 길이가 0이면 개체가 비어 있음을 알 수 있습니다.

function isEmpty(obj) {
    return Object.keys(obj).length === 0 && obj.constructor === Object;
}

Object.values 및 Object.entries를 사용하여 이를 확인할 수도 있습니다.일반적으로 개체가 비어 있는지 확인하는 가장 쉬운 방법입니다.

…에 대한 개체 속성 루프 지정

for…in 문은 개체의 열거 가능한 속성을 순환합니다.

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

    return true;
}

위의 코드에서, 우리는 객체 속성을 반복할 것이고, 만약 객체가 적어도 하나의 속성을 가지고 있다면, 그것은 루프에 들어가서 false를 반환할 것입니다.개체에 속성이 없으면 true가 반환됩니다.

#3. JSON.stringify를 사용하여 객체를 문자열화하고 결과가 단순히 여는 괄호와 닫는 괄호라면 객체가 비어 있음을 알 수 있습니다.

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

jQuery 사용

jQuery.isEmptyObject(obj); 

언더스코어 및 Lodash

_.isEmpty(obj);

자원

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

정답은 다음과 같습니다.

function isEmptyObject(obj) {
  return (
    Object.getPrototypeOf(obj) === Object.prototype &&
    Object.getOwnPropertyNames(obj).length === 0 &&
    Object.getOwnPropertySymbols(obj).length === 0
  );
}

다음 사항을 확인합니다.

  • 물체의 물의원정확히은형입니다.Object.prototype.
  • 개체에는 열거 가능성에 관계없이 고유한 속성이 없습니다.
  • 개체에 고유한 속성 기호가 없습니다.

즉, 객, 체, 는으로 만들어진 과 구별할 수 .{}.

다음 예제는 JavaScript 개체가 비어 있는지 테스트하는 방법을 보여줍니다. 빈 개체는 자체 속성이 없습니다.

이 스크립트는 ES6에서 작동합니다.

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

에는 한 기능이 있습니다.isEmptyObject() 예:

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

http://api.jquery.com/jQuery.isEmptyObject/ 에서 더 읽기

정말로 오직 받아들이는 것. {}자바스크립트에서 Lodash를 사용하는 가장 좋은 방법은 다음과 같습니다.

_.isEmpty(value) && _.isPlainObject(value)

Thevs 이외에도 다음과 같은 답변이 있습니다.

var o = {};
alert($.toJSON(o)=='{}'); // true

var o = {a:1};
alert($.toJSON(o)=='{}'); // false

jquery + jquery.json입니다.

주의! JSON의 한계에 주의하세요.

javascript:
  obj={  f:function(){}  };
  alert( "Beware!! obj is NOT empty!\n\nobj = {  f:function(){}  }" + 
               "\n\nJSON.stringify( obj )\n\nreturns\n\n" +
                        JSON.stringify( obj ) );

진열품

조심해요!!obj는 비어 있지 않습니다!
obj = {f:function(함수):{} }
JSON.stringify(obj )
돌아온다
{}

순수 Vanilla Javascript 및 완벽한 이전 버전과의 호환성

function isObjectDefined (Obj) {
  if (Obj === null || typeof Obj !== 'object' ||
    Object.prototype.toString.call(Obj) === '[object Array]') {
    return false
  } else {
    for (var prop in Obj) {
      if (Obj.hasOwnProperty(prop)) {
        return true
      }
    }
    return JSON.stringify(Obj) !== JSON.stringify({})
  }
}

console.log(isObjectDefined()) // false
console.log(isObjectDefined('')) // false
console.log(isObjectDefined(1)) // false
console.log(isObjectDefined('string')) // false
console.log(isObjectDefined(NaN)) // false
console.log(isObjectDefined(null)) // false
console.log(isObjectDefined({})) // false
console.log(isObjectDefined([])) // false
console.log(isObjectDefined({a: ''})) // true

다른 대안은 jquery(32kB), lodash(50kB) 또는 언더스코어(16.4kB)가 아닌 .js(14kB)를 사용하는 것입니다.js는 개체가 비어 있는지 여부를 확인하는 데 사용할 수 있는 앞서 언급한 라이브러리 중 가장 빠른 라이브러리로 입증되었습니다.

http://jsperf.com/check-empty-object-using-libraries

분명히 이 모든 라이브러리는 정확히 같지 않기 때문에 DOM을 쉽게 조작해야 한다면 jquery가 여전히 좋은 선택이거나 단순히 유형 검사 이상이 필요하다면 lodash 또는 밑줄이 좋을 수 있습니다.is.js에 대해서는 다음과 같은 구문이 있습니다.

var a = {};
is.empty(a); // true
is.empty({"hello": "world"}) // false

언더코어로것처럼의다와쉬스▁▁like._.isObject()이것은 전용이 아닙니다.objects 에도적다니됩용에도 됩니다.arrays그리고.strings.

는 후드 에서 이라브리후아서래에드가를 합니다.Object.getOwnPropertyNames은 한유사와 합니다.Object.keys그렇지만Object.getOwnPropertyNames는 여기에 설명된 대로 열거 가능한 속성과 열거 불가능한 속성을 반환하기 때문에 더욱 철저합니다.

is.empty = function(value) {
    if(is.object(value)){
        var num = Object.getOwnPropertyNames(value).length;
        if(num === 0 || (num === 1 && is.array(value)) || (num === 2 && is.arguments(value))){
            return true;
        }
        return false;
    } else {
        return value === '';
    }
};

라이브러리를 가져오지 않으려는 경우(이해할 수 있음) 개체만 확인하는 경우(배열이나 문자열이 아님) 다음 기능이 필요에 적합합니다.

function isEmptyObject( obj ) {
    return Object.getOwnPropertyNames(obj).length === 0;
}

이것은 is.js보다 조금 더 빠르지만, 단지 당신이 그것이 객체인지 확인하지 않기 때문입니다.

어떤 항목이 존재하는 것과 반대로 객체의 값을 비교하는 해결책을 만나지 못한 것이 이상합니다(아마도 주어진 많은 해결책 중에서 놓쳤을 것입니다).
모든 값이 정의되지 않은 경우 개체가 비어 있는 것으로 간주되는 경우를 다루고 싶습니다.

    const isObjectEmpty = obj => Object.values(obj).every(val => typeof val === "undefined")

    console.log(isObjectEmpty({}))                                 // true
    console.log(isObjectEmpty({ foo: undefined, bar: undefined })) // true
    console.log(isObjectEmpty({ foo: false,     bar: null }))      // false

사용 예

를 들어(당數, 가있하자예고다함지고를, 신이수어들를하▁(▁(자)를 있다고 paintOnCanvas하는 ( ) ( ) 서값파괴는하을에인수 ( )x,y그리고.size) 모든 항목이 정의되지 않은 경우, 결과 옵션 집합에서 제외됩니다.그렇지 않으면 모두 포함됩니다.

function paintOnCanvas ({ brush, x, y, size }) {
  const baseOptions = { brush }
  const areaOptions = { x, y, size }
  const options = isObjectEmpty(areaOptions) ? baseOptions : { ...baseOptions, areaOptions }
  // ...
}

내가 찾을 수 있는 최고의 한 줄 솔루션(업데이트):

isEmpty = obj => !Object.values(obj).filter(e => typeof e !== 'undefined').length;

console.log(isEmpty({}))                                        // true
console.log(isEmpty({a: undefined, b: undefined}))              // true
console.log(isEmpty({a: undefined, b: void 1024, c: void 0}))   // true

console.log(isEmpty({a: [undefined, undefined]}))               // false
console.log(isEmpty({a: 1}))                                    // false
console.log(isEmpty({a: ''}))                                   // false
console.log(isEmpty({a: null, b: undefined}))                   // false

Is Empty Object는 Yahoo의 유명한 구루가 ECMA에 사용자 정의된 열거할 수 없는 개체 속성을 도입하고 수락했을 때 뜻하지 않게 의미를 잃었습니다.

[ 역사가 마음에 들지 않으면 언제든지 작업 코드로 건너뜁니다.]

저는 이 질문에 대한 많은 좋은 대답들을 보고 있습니다 \ 해결책 \그러나 ECMA Script에 대한 최신 확장 기능을 확보하는 것은 올바른 방법이 아닙니다.우리는 Netscape 4.x와 Netscape 기반의 페이지 작업 및 프로젝트를 활성화하기 위해 예전에 웹을 보류하곤 했는데, 이는 (참고로) 매우 원시적이고 특이했습니다.새로운 W3C 표준과 제안을 사용하는 것을 거부하는 동시에 지금은 우리 자신의 유산에 대해 잔인합니다.

인터넷 익스플로러 11을 죽이는 것은 명백히 잘못된 것입니다!네, "냉전" 시대 이후로 마이크로소프트에 잠자고 있던 일부 늙은 전사들은 잘못된 이유로 그것에 동의했습니다. - 하지만 그것은 옳지 않습니다!

답변에 새로 도입된 방법\특성을 사용하여 새로운 발명품(실제 발명품)이 아닌 발견물("항상 존재했지만 우리는 알아차리지 못했습니다.")로 넘기는 것은 다소 '친환경적'이고 해롭습니다.저는 20년 전에 그런 실수를 하곤 했습니다. 그 때 저는 아직도 그 안에 무엇이 있는지 구분하지 못했고 제가 참고할 수 있는 모든 것을 공통의 해결책으로 취급했습니다.

이전 버전과의 호환성이 중요합니다.

우리는 아직 그것을 모릅니다.이러한 이유로 저는 예측할 수 없는 미래에 대해 앞뒤로 호환되는 '수세기 전의' 일반 솔루션을 공유해야 했습니다.

in 연산자에 대한 많은 공격들이 있었지만, 저는 그것을 하는 사람들이 마침내 깨달았고 자바스크립트와 같은 진정한 동적 유형 언어와 아름다운 자연을 이해하고 감사하기 시작했다고 생각합니다.

제 방법은 단순하고 핵적인 것을 목표로 하고 있으며 위에서 언급한 이유로 저는 그 단어의 의미가 더 이상 정확하지 않기 때문에 "빈"이라고 부르지 않습니다.Is Enumerable, 정확한 의미를 가진 단어인 것 같습니다.

function isEnum( x ) { for( var p in x )return!0; return!1 };

일부 사용 사례:

isEnum({1:0})
true

isEnum({})
false

isEnum(null)
false

읽어주셔서 감사합니다!

Sugar.JS는 이 목적을 위해 확장 개체를 제공합니다.코드는 깨끗하고 간단합니다.

확장 개체 만들기:

a = Object.extended({})

크기 확인:

a.size()

이것이 귀하의 질문에 100% 답하지는 않지만, 이전에도 비슷한 문제에 직면한 적이 있으며, 이 문제를 해결하기 위해 사용하는 방법은 다음과 같습니다.

빈 개체를 반환할 수 있는 API가 있습니다.API에서 어떤 필드를 예상해야 하는지 알고 있기 때문에 필요한 필드가 있는지 여부만 확인합니다.

예:

API 반환{} or {agentID: '1234' (required), address: '1234 lane' (opt),...}내 호출 기능에서, 나는 단지 확인할 뿐입니다.

if(response.data && response.data.agentID) { 
  do something with my agentID 
} else { 
  is empty response
}

이렇게 하면 개체가 비어 있는지 확인하기 위해 값비싼 방법을 사용할 필요가 없습니다.개체에 에이전트가 없는 경우 호출 기능에 대해 개체가 비어 있습니다.ID 필드.

이 한 줄 코드는 이전 브라우저로의 폴백에도 도움이 됩니다.

var a = {}; //if empty returns false
(Object.getOwnPropertyNames ? Object.getOwnPropertyNames(a).length !== 0 : (function(){ for(var key in a) break; return !!key })()) //Returns False

var a = {b:2}; //if not empty returns true
(Object.getOwnPropertyNames ? Object.getOwnPropertyNames(a).length !== 0 : (function(){ for(var key in a) break; return !!key })()) //Returns true

Object.getOwnPropertyNames는 ECMA-5에 구현되어 있습니다. 위의 줄은 폴백 기능이 있는 이전 브라우저에서 작동합니다.


또 다른 빠른 해결책은 다음을 확인하는 것입니다.length, 또는 의 속성.

지식 기사:개체의 자세한 차이점은 이 SO 게시물을 참조하십시오.키와 Object.getOownPropertyNames 비교

다음과 같이 null 또는 uninfined check를 처리하는 vanilla js로 확인할 수 있습니다.

function isEmptyObject(obj) {
  return !!obj && Object.keys(obj).length === 0 && obj.constructor === Object;
}

//tests

isEmptyObject(new Boolean());  // false 
isEmptyObject(new Array());    // false 
isEmptyObject(new RegExp());   // false 
isEmptyObject(new String());   // false 
isEmptyObject(new Number());   // false 
isEmptyObject(new Function()); // false 
isEmptyObject(new Date());     // false
isEmptyObject(null);          // false
isEmptyObject(undefined);     // false
isEmptyObject({});            // true

언급URL : https://stackoverflow.com/questions/679915/how-do-i-test-for-an-empty-javascript-object

반응형