Is there a jQuery way of iterating over an objects

2019-06-27 04:51发布

I'm making a small jQuery-like library, and one thing striking me odd is the behavior of $.each.

In javascript we have a for...in loop:

for (var key in obj) {
    console.log(key + ': ' + obj[key]);
}

The problem with this, is that it will iterate over inherited properties as well, that is, properties coming from the object constructor's prototype.

One can know this using hasOwnProperty, for example. And jQuery could do that.

But, when you pass an object to $.each, it behaves exactly like a for...in, iterating over inherited properties as well. It also should be marginally slower, and requires a few more characters to type.

Check this fiddle to see it in action and look here for the source code of $.each.

So my question is, is there an object iteration method in jQuery that only includes own properties? If not, should a library behave like this?

Edit: Since jQuery does not do this, you can also answer if this is useful. I mean, I cannot see myself wanting to iterate over prototype properties, but maybe I'm missing something.

1条回答
神经病院院长
2楼-- · 2019-06-27 05:22

The jQuery behavior makes sense, as you can always choose to add the hasOwnProperty check in the loop - or not.

I can see that looping through inherited properties could be useful in some scenarios (cloning or sub-class or whatever you call it).

查看更多
登录 后发表回答