for...in 循环在 JavaScript 中有用吗?
我是 JavaScript 新手,目前正在学习所谓的 for...in
循环。
在 JavaScript 中编码时,人们真的会使用这些循环吗?
我可以看到所有其他类型的循环是如何有用的——但不是这个。
请有人对此进行阐明,并在可能的情况下提供一个现实生活中的示例。
I'm new to JavaScript, and I'm currently learning about the so-called for... in
loop.
Does one actually use those loops when coding in JavaScript?
I can see how all other types of loops are useful — but not this one.
Someone shed some light on this please and include a real life example if possible.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
在 Javascript 中,只有 Array 对象可以使用普通的
for(;;)
循环进行迭代。for..in
用于枚举非数组对象:In Javascript only Array objects can be iterated with a normal
for(;;)
loop. Thefor..in
is used for enumeration of non-array objects:它通常用于循环某些内容的集合。例如,由于每个 JavaScript 对象都可以视为属性的集合,因此您可以通过这种方式枚举属性。
It is typically used to loop over a collection of something. For instance, since every JavaScript object can be treated as a collection of properties, you can enumerate properties in this manner.
我认为只要您了解对象可以容纳的不仅仅是简单的变量,就可以了。考虑这个从 w3schools.com 修改的示例来说明这一点:
打印:
string string number function
为了回答有关循环类型之间差异的具体问题,for() 循环非常适合具有 length 属性的数组类型。 foreach() 循环可以很好地用于迭代对象集合,而 foreach ...in 循环可以很好地用于对象的键(不声称这些是任何循环类型的独占用途)。
I think it's OK so long as you understand that an object can hold more than simple variables. Consider this example, modified from w3schools.com to illustrate the point:
This prints:
string string number function
To answer your specific question about the differences between loop types, the for() loop works well for array types with a length property. The foreach() loop can work well for iterating over collections of objects, while the foreach ...in loop works well for keys of an object (Not claiming that these are exclusive uses for any of the loop types).
要理解这一点,您首先需要了解 JavaScript 的对象模型。
正如您所注意到的,在处理数组时,
for...in
循环并不是那么有用,因为for (;;)
循环更容易完成这项工作。但数组只是一种具有数字属性的 JavaScript 对象,而 for (;;) 循环仅处理数字属性。使用
myArray[0]
表示法的原因是您可以对任何属性名称使用此方括号表示法。因此myObject['myProperty']
与myObject.myProperty
相同。这就是for...in
变得有用的地方:因此,如果我们设置的唯一属性是
myProperty
,那么i
将等于>“myProperty”
(请注意,它是一个字符串,这使其比仅仅作为变量名称更加动态)。但这里有一个巨大的“但是”。对象有一个叫做原型的东西,这些原型有自己的属性和方法。如果我执行以下操作:
...我不仅会收到数值(1、2、3 等)的警报,还会收到数组属性的警报,例如
length
,及其方法,例如join
。这些属性实际上属于 Array 对象的原型,并且可以通过执行以下操作来过滤原型属性:现在我将再次收到数值警报,这意味着这(几乎)与
for 完全相同(var i = 0;; i < myArray.length; i++)
。当我们可以使用该符号时,为什么我要告诉你这个?因为所有对象都有原型,而不仅仅是数组。每个对象都源自Object
对象,因此如果有人定义了Object.prototype.myProperty = "some string value"
那么它总是会出现在任何for 中...in
循环,用于页面的其余部分。值得庆幸的是,hasOwnProperty
方法本身属于Object.prototype
,因此您可以(并且应该)始终在for...in
中使用它循环。所以这是一个成熟的
for...in
示例:输出:
希望这能解释一切。
To understand this, you first need to understand JavaScript's object model.
As you'll have noted, when working with arrays,
for...in
loops aren't that useful becausefor (;;)
loops do the job more easily.But arrays are just a type of JavaScript object with numeric properties, and
for (;;)
loops only handle numeric properties. The reason for the notationmyArray[0]
is that you can use this square bracket notation for any property name. SomyObject['myProperty']
is the same asmyObject.myProperty
. This is wherefor...in
becomes useful:So if the only property we'd set was
myProperty
, theni
would equal"myProperty"
(note that it's a string, which makes it more dynamic than just being a variable name).There's a huge BUT here though. Objects have something called a prototype, and these prototypes have their own properties and methods. If I do the following:
...I won't just get alerted with numeric values (1, 2, 3, etc.) I'll also get alerted with the array's properties such as
length
, and its methods such asjoin
. These properties actually belong to the Array object's prototype, and the prototype properties can be filtered out by doing the following:Now I'll just get alerted with numeric values again, which means this is (almost) exactly the same as
for (var i = 0;; i < myArray.length; i++)
. Why am I telling you this when we can just use that notation? Because all objects have prototypes, not just arrays. And every object descends from theObject
object, so if somebody definedObject.prototype.myProperty = "some string value"
then that would always show up in anyfor...in
loop you use in the rest of the page. Thankfully, thehasOwnProperty
method itself belongs toObject.prototype
, so you can (and should) always use it in yourfor...in
loops.So here's a fully fledged
for...in
example:Output:
Hopefully this explains it all.
for in
和for
都有特定的用途。让我们看一些。如果你有一个对象
,那么你可以使用
for in
循环迭代它的属性,即注意,如果你尝试通过for迭代
obj
循环它不会工作,因为它会使用数字索引来访问键并且会给出一个未定义的,即 obj[0] 将会是未定义的。这与获取对象的长度比简单地编写 obj.length 更复杂这一事实无关。当然,如果您有数字属性,您将能够使用for
循环,for in
只是更自然地适合对象迭代。如果您有一个数组,
从技术上讲您可以同时使用这两个但,建议您为此使用 for 循环。这就是为什么
为了说明第二点,让我们扩展 Array。
我们刚刚添加到 Array 的这个函数将被所有 Array 对象继承,因此,通过
for in
迭代数组会产生收益
,并且使用
for
迭代数组将产生预期的结果。
因此,对于对象迭代,请使用
for in
;对于数组迭代,请使用for
Both
for in
andfor
serve specific purposes. Let's look at some.If you have an object
Then you can iterate over it's properties using the
for in
loop i.enote, if you try to iterate
obj
via a for loop it wouldn't work because it would use numeric indexes to access the keys and would give an undefined i.eobj[0]
would be undefined. This is aside form the fact that getting the length of an object would be more involved than simply writingobj.length
. Of course if you had numeric properties you would be able to use thefor
loop,for in
is just a more natural fit for object iteration.If you have an array
you could technically use both but it's recommended that you use the for loop for this. Here's why
To illustrate point two, let's extend Array.
This function that we just added to Array will be inherited by all Array objects, hence, iterating over the array via a
for in
Would yield
And iterating over the array with the
for
would yield the expected result.
Hence, for object iteration use the
for in
and for array iteration use thefor