这个函数如何确定一个对象是空的? [英] How does this function determine of an object is empty?

查看:83
本文介绍了这个函数如何确定一个对象是空的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在挖掘jQuery源代码,我发现他们使用这个小代码片段来检测JavaScript对象是否为空。

I was digging around the jQuery source code and I found that they use this little code snippet to detect if a JavaScript object is empty.

function isMyObjEmpty( obj ) {
    var name;
    for (name in obj ) {
        return false;
    }
    return true;
}

有人能解释一下为什么会这样吗?我只是不明白为什么这会回归真实。

Can someone explain to me why this works? I just don't understand why this would ever return true.

推荐答案

为什么会这样:



这使用 for ... in 循环迭代对象的属性。

Why it works:

This uses a for... in loop to iterate through the object's properties.

如果对象有任何属性,它将进入循环并返回 false

If the object has any property, it would enter the loop and return false

如果对象没有属性,它将不会进入循环,并返回 true

If the object has no properties, it would not enter the loop, and return true.

请注意,存在这种情况不起作用。 for .. in 循环只能通过 enumerable 属性,所以从技术上讲,一个对象可以是非空的,它仍会返回假。可以定义属性可枚举并欺骗这种方法。 以下是有问题的案例

Note that there exists a case where it does not work. for.. in loops only go through enumerable properties so technically an object can be non-empty and it would still return false. One can define a property to not be enumerable and trick this method. Here is the problematic case.

正确的说法是,此方法检查对象是否具有任何可枚举属性。

The correct thing to say is that this method checks if an object has any enumerable properties.

您可以在此处找到方法的文档

You can find the method's documentation here.


描述:检查一个对象是否为空(不包含可枚举的属性)。

Description: Check to see if an object is empty (contains no enumerable properties).

我个人觉得很奇怪他们会调用该方法 isEmptyObject 。我认为更合适的名称是 hasNoEnumerableProperties

I personally find it odd they would call that method isEmptyObject. I think a better suited name would be hasNoEnumerableProperties.

在JS的新实现中,可以使用 Object.getOwnPropertyNames getOwnPropertyNames 获取所有属性,可枚举与否。

In newer implementations of JS one can use Object.getOwnPropertyNames. getOwnPropertyNames gets all the properties, enumerable or not.

您可以使用 Object.getOwnPropertyNames(myObject)实现 isMyObjEmpty .length === 0 。这将检查对象是否没有可枚举的属性。

You can implement isMyObjEmpty with Object.getOwnPropertyNames(myObject).length===0. This checks that the object has no properties, enumerable or not.

但是,这并不会检查原型属性。这可能是,也可能不是理想的行为,您可以查看我对 shadowmonkey 的讨论。通过调用 <$可以轻松解决这个问题。递归地c $ c> Object.getPrototypeOf 并检查原型链中的属性。

This however, does not check prototypical properties though. This might, or might not be desirable behavior, you can check the discussion I've had with theshadowmonkey about it. That could be easily solved by making a call to Object.getPrototypeOf recursively and checking for properties across the prototypical chain.

这篇关于这个函数如何确定一个对象是空的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆