博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
对象是空的吗? [重复]
阅读量:2290 次
发布时间:2019-05-09

本文共 1694 字,大约阅读时间需要 5 分钟。

本文翻译自:

This question already has answers here :
这个问题已经在这里有了答案
(46 answers)
(46个答案)
Closed 2 years ago .
2年前关闭。

What is the fastest way to check if an object is empty or not? 检查对象是否为空的最快方法是什么?

Is there a faster and better way than this: 有没有比这更快更好的方法:

function count_obj(obj){    var i = 0;    for(var key in obj){        ++i;    }    return i;}

#1楼

参考:


#2楼

EDIT : Note that you should probably use instead of this since ES5 support is these days. 编辑 :请注意,您可能应该使用而不是使用此 ,因为近来对ES5的支持非常 。 It still works for jQuery though. 它仍然适用于jQuery。


Easy and cross-browser way is by using jQuery.isEmptyObject : 简单而跨浏览器的方法是使用jQuery.isEmptyObject

if ($.isEmptyObject(obj)){    // do something}

More: 更多: :

You need jquery though. 你需要jQuery。


#3楼

No need for a library. 无需图书馆。

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

#4楼

if (Object.getOwnPropertyNames(obj1).length > 0){ alert('obj1 is empty!');}

#5楼

快速在线搜索“字典”对象:

function isEmptyDict(d){for (var k in d) return false; return true}

#6楼

You can write a fallback if Array.isArray and Object.getOwnPropertyNames is not available 如果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;}

转载地址:http://cpcnb.baihongyu.com/

你可能感兴趣的文章
LeetCode之Median Of Two Sorted Arrays
查看>>
LeetCode之Longest Palindromic Substring
查看>>
Leetcode之Implement strStr()
查看>>
Leetcode之Divide Two Integers
查看>>
Leetcode之Next Permutation (Medium)
查看>>
关于初学者上传文件到github的方法
查看>>
Leetcode之Reverse Nodes in k-Group (Hard)
查看>>
Leetcode之Combination SumII
查看>>
libpython2.7.a(abstract.o) recompile with -fPIC
查看>>
Leetcode之Substring with Concatenation of All Words
查看>>
Leetcode之first missing positive
查看>>
Leetcode之Sort List
查看>>
Leetcode之Remove Duplicate Letters
查看>>
java.util.Stack类简介
查看>>
JAVA的一次编译,到处运行,你知道多少?
查看>>
ClassLoader源码分析
查看>>
Java内存泄露的理解与解决
查看>>
Leetcode之super ugly number
查看>>
堆 (heap)
查看>>
[Leetcode之Search in Rotated Sorted Array II (Java)
查看>>