简体   繁体   English

通过.length检查对象是否存在

[英]Checking if an object exists via .length

JSFiddle: https://jsfiddle.net/pd08dgxu/1/ JSFiddle: https ://jsfiddle.net/pd08dgxu/1/

I need to check whether a JavaScript object is empty or not. 我需要检查JavaScript对象是否为空。 Suppose, in this fiddle, Obj1 is not empty (it contains the fields below) but Obj2 is {} . 假设在这个小提琴中,Obj1不为空(它包含下面的字段),但是Obj2为{}

In both cases, when I check obj1.length or obj2.length , I get Undefined (see alert). 在这两种情况下,当我检查obj1.lengthobj2.length ,都会得到Undefined (请参阅警报)。 Shouldn't we check for existence by using the .length operator on all variables, whether strings or complex objects? 我们是否应该在所有变量(字符串或复杂对象)上使用.length运算符来检查是否存在?

function getObject() {
    return { 'color' : 'red', 
             'title' : 'my title'
    };
}

var myObj1 = getObject();
var myObj2 = {};  //empty object

alert('myObj1 Length = ' + myObj1.length + '  myObj2 Length = ' + myObj2.length);

You cannot check the object's existance using obj.length . 您不能使用obj.length来检查对象的存在。 You have to count the number of key s. 您必须计算key的数量。

Try Object.keys(Obj).length 尝试Object.keys(Obj).length

 function getObject() { return { 'color' : 'red', 'title' : 'my title' }; } var myObj1 = getObject(); var myObj2 = {}; //empty object console.log('myObj1 Length = ' + Object.keys(myObj1).length + ' myObj2 Length = ' + Object.keys(myObj2).length); 

The length property only works like that on Arrays. length属性只能像在Arrays上那样工作。

To get the number of properties on any object, you can use the Object.keys method, which returns an array of all the property-names on an object. 要获取任何对象上的属性数量,可以使用Object.keys方法,该方法返回对象上所有属性名称的数组。 Like this: Object.keys(Obj).length . 像这样: Object.keys(Obj).length

isEnum isEnum

Here is my conventional JavaScript singleton which is a part of all my util. 这是我常规的JavaScript单例,它是所有util的一部分。 libs. 库。

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

And it's faster than Object.keys in any aspect. 而且它在任何方面都比Object.keys更快。 Will work correctly in case you've accidentally dropped an Array in its argument instead of an Object. 万一您不小心将Array(而不是Object)放到了其参数中,它将正常工作。

It's use is exactly what you need it for to check if the object is empty or enumerable before deciding to iterate it or not. 它的用途恰恰是您需要使用它来检查对象是否为空或可枚举的,然后再决定是否对其进行迭代。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM