객체가 비어 있습니까?
물체가 비어 있는지 여부를 확인하는 가장 빠른 방법은 무엇입니까?
이것보다 더 빠르고 좋은 방법이 있을까요?
function count_obj(obj){
var i = 0;
for(var key in obj){
++i;
}
return i;
}
ECMAScript5(일부 브라우저에서는 아직 지원되지 않음)의 경우 다음을 사용할 수 있습니다.
Object.keys(obj).length === 0
공허하다는 것은 "자신의 소유물이 없다"는 뜻일 겁니다.
// Speed up calls to hasOwnProperty
var hasOwnProperty = Object.prototype.hasOwnProperty;
function isEmpty(obj) {
// null and undefined are "empty"
if (obj == null) return true;
// Assume if it has a length property with a non-zero value
// that that property is correct.
if (obj.length > 0) return false;
if (obj.length === 0) return true;
// If it isn't an object at this point
// it is empty, but it can't be anything *but* empty
// Is it empty? Depends on your application.
if (typeof obj !== "object") return true;
// Otherwise, does it have any properties of its own?
// Note that this doesn't handle
// toString and valueOf enumeration bugs in IE < 9
for (var key in obj) {
if (hasOwnProperty.call(obj, key)) return false;
}
return true;
}
예:
isEmpty(""), // true
isEmpty(33), // true (arguably could be a TypeError)
isEmpty([]), // true
isEmpty({}), // true
isEmpty({length: 0, custom_property: []}), // true
isEmpty("Hello"), // false
isEmpty([1,2,3]), // false
isEmpty({test: 1}), // false
isEmpty({length: 3, custom_property: [1,2,3]}) // false
ECMAScript5 브라우저만 취급하면 루프 대신 을 사용할 수 있습니다.
if (Object.getOwnPropertyNames(obj).length > 0) return false;
에 의해, 속성만이 에서도, 할 수.isEmpty
을 사용법
편집: 현재 ES5 지원이 널리 보급되어 있기 때문에 ES5 솔루션을 사용하는 것이 좋습니다.jQuery에서는 아직 동작합니다.
은 "Cross-Browser"를 사용하는 입니다.jQuery.isEmptyObject
:
if ($.isEmptyObject(obj))
{
// do something
}
상세: http://api.jquery.com/jQuery.isEmptyObject/
하지만 당신은 jquery가 필요해요.
밑줄과 로다시는 각각 편리한 점이 있습니다.isEmpty()
라이브러리 추가가 괜찮으시다면 기능을 이용하세요.
_.isEmpty({});
Node, Chrome, Firefox 및 IE 9에서 테스트한 결과 대부분의 사용 사례에서 다음과 같은 사실이 확인되었습니다.
- (...in...용)이 가장 빠른 옵션입니다!
- 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;
}
노드 아래의 결과:
- 번째 결과: " " " 입니다.
return (Object.keys(obj).length === 0)
- 결과: " " " " 입니다.
for (var x in obj) { return false; }...
- 결과: " " " 입니다.
for (var x in obj) { if (obj.hasOwnProperty(x)) return false; }...
- 결과: 4번째 결과:
return ('{}' === JSON.stringify(obj))
키가 0.00018 0.000015 0.000015 0.000324인 오브젝트 테스트
키가 0.000346 0.000458 0.000577 0.000657인 오브젝트 테스트
키가 0.000375 0.00046 0.000565 0.000773인 오브젝트 테스트
3개의 키가 0.000406 0.000476 0.000577 0.000904인 오브젝트 테스트
키가 0.000435 0.000487 0.000589 0.001031인 오브젝트 테스트
5 키 0.000465 0.000501 0.000604 0.001148을 사용한 객체 테스트
6개의 키가 0.000492 0.000511 0.000618 0.001269인 오브젝트 테스트
7 키 0.000528 0.000527 0.000637 0.00138을 사용한 객체 테스트
키가 0.000565 0.000538 0.000647 0.00159인 오브젝트 테스트
키가 100인 오브젝트 테스트0.003718 0.00243 0.002535 0.01381
1000 키 0.0337 0.0193 0.0194 0.1337을 사용한 객체 테스트
일반적인 사용 사례에서 키가 적은 빈 개체를 테스트하고 키가 10개 이상인 빈 개체 또는 개체를 테스트하는 경우가 거의 없는 경우 Object.keys(obj)를 고려하십시오.length 옵션. - 그렇지 않으면 보다 일반적인 (...의 경우) 구현을 사용합니다.
Firefox가 Object.keys(obj)를 더 빠르게 지원하는 것 같습니다.length 및 Object.getOwnPropertyNames(obj)를 지정합니다.길이가 비어 있지 않은 오브젝트에 더 적합합니다만, 빈 오브젝트에 관해서는 (...in...의 경우)가 10배 빨라집니다.
제 2센트는 그 Object.keys(obj)입니다.length는 키의 오브젝트를 생성하기 때문에 파기하는 것보다 안에 있는 키의 수를 세는 것이 바람직하지 않습니다.그 물체를 만들기 위해서는 키를 바깥쪽으로 돌려야 해(... in...의 경우) 옵션이 아니라 왜 사용하는가?
var a = {};
function timeit(func,count) {
if (!count) count = 100000;
var start = Date.now();
for (i=0;i<count;i++) func();
var end = Date.now();
var duration = end - start;
console.log(duration/count)
}
function isEmpty1() {
return (Object.keys(a).length === 0)
}
function isEmpty2() {
for (x in a) { return false; }
return true;
}
function isEmpty3() {
for (x in a) { if (a.hasOwnProperty(x)) return false; }
return true;
}
function isEmpty4() {
return ('{}' === JSON.stringify(a))
}
for (var j=0;j<10;j++) {
a = {}
for (var i=0;i<j;i++) a[i] = i;
console.log('Testing for Object with '+Object.keys(a).length+' keys')
timeit(isEmpty1);
timeit(isEmpty2);
timeit(isEmpty3);
timeit(isEmpty4);
}
a = {}
for (var i=0;i<100;i++) a[i] = i;
console.log('Testing for Object with '+Object.keys(a).length+' keys')
timeit(isEmpty1);
timeit(isEmpty2);
timeit(isEmpty3);
timeit(isEmpty4, 10000);
a = {}
for (var i=0;i<1000;i++) a[i] = i;
console.log('Testing for Object with '+Object.keys(a).length+' keys')
timeit(isEmpty1,10000);
timeit(isEmpty2,10000);
timeit(isEmpty3,10000);
timeit(isEmpty4,10000);
우아한 방법 - 키 사용
var myEmptyObj = {};
var myFullObj = {"key":"value"};
console.log(Object.keys(myEmptyObj).length); //0
console.log(Object.keys(myFullObj).length); //1
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
function isEmpty( o ) {
for ( var p in o ) {
if ( o.hasOwnProperty( p ) ) { return false; }
}
return true;
}
var x= {}
var y= {x:'hi'}
console.log(Object.keys(x).length===0)
console.log(Object.keys(y).length===0)
true
false
http://jsfiddle.net/j7ona6hz/1/
이렇게 기본적인 JS 질문에 너무 많은 미숙한 답변들을 보고 깜짝 놀랐습니다.위의 답변도 다음과 같은 이유로 좋지 않습니다.
- 글로벌 변수를 생성합니다.
- 돌아온다
true
에undefined
- 사용하다
for...in
그 자체로 매우 느리다. - 안에서 기능하다
for...in
쓸모없다 - 반품false
없이.hasOwnProperty
마법은 잘 통할 것이다
실제로 다음과 같은 간단한 솔루션이 있습니다.
function isEmpty(value) {
return Boolean(value && typeof value === 'object') && !Object.keys(value).length;
}
https://lodash.com/docs#isEmpty은 매우 편리합니다.
_.isEmpty({}) // true
_.isEmpty() // true
_.isEmpty(null) // true
_.isEmpty("") // true
얼마나 안 좋은가요?
function(obj){
for(var key in obj){
return false; // not empty
}
return true; // empty
}
라이브러리는 필요 없습니다.
function(){ //must be within a function
var obj = {}; //the object to test
for(var isNotEmpty in obj) //will loop through once if there is a property of some sort, then
return alert('not empty')//what ever you are trying to do once
return alert('empty'); //nope obj was empty do this instead;
}
좀 허술할 수도 있어요.이거 드셔보세요.
if (JSON.stringify(data).length === 2) {
// Do something
}
이 방법에 단점이 있는지 잘 모르겠습니다.
'보통'을 위한 빠른 온라인 라이너:
function isEmptyDict(d){for (var k in d) return false; return true}
Array.isArray 및 Object.getOwnPropertyNames를 사용할 수 없는 경우 폴백을 작성할 수 있습니다.
XX.isEmpty = function(a){
if(Array.isArray(a)){
return (a.length==0);
}
if(!a){
return true;
}
if(a instanceof Object){
if(a instanceof Date){
return false;
}
if(Object.getOwnPropertyNames(a).length == 0){
return true;
}
}
return false;
}
다음과 같은 오브젝트가 있다고 가정합니다.
var obj1= {};
var obj2= {test: "test"};
=== 기호는 상속을 받을 때 객체 동일성을 테스트하는 데 사용할 수 없으므로 ECMA 5 이상 버전 javascript를 사용하면 답이 간단합니다.
function isEmpty(obj) {
//check if it's an Obj first
var isObj = obj !== null
&& typeof obj === 'object'
&& Object.prototype.toString.call(obj) === '[object Object]';
if (isObj) {
for (var o in obj) {
if (obj.hasOwnProperty(o)) {
return false;
break;
}
}
return true;
} else {
console.error("isEmpty function only accept an Object");
}
}
결과는 다음과 같습니다.
isEmpty(obj1); //this returns true
isEmpty(obj2); //this returns false
isEmpty([]); // log in console: isEmpty function only accept an Object
funtion isEmpty(o,i)
{
for(i in o)
{
return!1
}
return!0
}
여기 그것을 하는 좋은 방법이 있다.
function isEmpty(obj) {
if (Array.isArray(obj)) {
return obj.length === 0;
} else if (typeof obj === 'object') {
for (var i in obj) {
return false;
}
return true;
} else {
return !obj;
}
}
var hasOwnProperty = Object.prototype.hasOwnProperty;
function isArray(a) {
return Object.prototype.toString.call(a) === '[object Array]'
}
function isObject(a) {
return Object.prototype.toString.call(a) === '[object Object]'
}
function isEmpty(a) {
if (null == a || "" == a)return!0;
if ("number" == typeof a || "string" == typeof a)return!1;
var b = !0;
if (isArray(a)) {
if (!a.length)return!0;
for (var c = 0; c < a.length; c++)isEmpty(a[c]) || (b = !1);
return b
}
if (isObject(a)) {
for (var d in a)hasOwnProperty.call(a, d) && (isEmpty(a[d]) || (b = !1));
return b
}
return!0
}
다음과 같은 결정을 내릴 수 있습니다.
var isEmpty = function(obj) {
for (var key in obj)
if(obj.hasOwnProperty(key))
return false;
return true;
}
내 필요에 맞게 션 비에이라의 코드를 수정했어null 및 defined는 개체로 전혀 카운트되지 않으며 숫자, 부울 값 및 빈 문자열은 false를 반환합니다.
'use strict';
// Speed up calls to hasOwnProperty
var hasOwnProperty = Object.prototype.hasOwnProperty;
var isObjectEmpty = function(obj) {
// null and undefined are not empty
if (obj == null) return false;
if(obj === false) return false;
if(obj === true) return false;
if(obj === "") return false;
if(typeof obj === "number") {
return false;
}
// Assume if it has a length property with a non-zero value
// that that property is correct.
if (obj.length > 0) return false;
if (obj.length === 0) return true;
// Otherwise, does it have any properties of its own?
// Note that this doesn't handle
// toString and valueOf enumeration bugs in IE < 9
for (var key in obj) {
if (hasOwnProperty.call(obj, key)) return false;
}
return true;
};
exports.isObjectEmpty = isObjectEmpty;
여기 나의 해결책
function isEmpty(value) {
if(Object.prototype.toString.call(value) === '[object Array]') {
return value.length == 0;
} else if(value != null && typeof value === 'object') {
return Object.getOwnPropertyNames(value).length == 0;
} else {
return !(value || (value === 0));
}
}
외치다
if (Object.getOwnPropertyNames(obj1).length > 0)
{
alert('obj1 is empty!');
}
언급URL : https://stackoverflow.com/questions/4994201/is-object-empty
'itsource' 카테고리의 다른 글
Java가 히프 크기(또는 도커 메모리 제한 크기)보다 훨씬 많은 메모리를 사용합니다. (0) | 2022.11.05 |
---|---|
mysql 액세스 거부 이벤트허가 권한이 존재함 (0) | 2022.11.05 |
IF 문을 사용할 때 MariaDB 구문 오류 발생 (0) | 2022.11.05 |
MySQL: 오류 코드: 1118 행 크기가 너무 큽니다(> 8126).일부 열을 TEXT 또는 BLOB로 변경 (0) | 2022.11.05 |
JavaScript에서 "assert"란 무엇입니까? (0) | 2022.11.05 |