在 JavaScript 中循环遍历数组
在 Java 中,您可以使用 for
循环来遍历数组中的对象,如下所示:
String[] myStringArray = {"Hello", "World"};
for (String s : myStringArray) {
// Do something
}
我可以在 JavaScript 中执行相同的操作吗?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(30)
我认为最好的方法是使用 Array.forEach 函数。如果你不能使用它,我建议从 MDN 获取 polyfill。为了使其可用,这无疑是在 JavaScript 中迭代数组的最安全方法。
Array.prototype.forEach()
正如其他人所建议的,这几乎总是您想要的:
这确保您在处理数组的范围内所需的任何内容都保留在该范围内,并且您只处理数组的值,不是对象属性和其他成员,这就是
for ..
in 的作用。在大多数情况下,使用常规 C 风格的
for
循环是可行的。重要的是要记住循环中的所有内容都与程序的其余部分共享其作用域,{} 不会创建新的作用域。因此:
将输出“11” - 这可能是也可能不是您想要的。
一个有效的 jsFiddle 示例:
https://jsfiddle.net/workingClassHacker/pxpv2dh5/7/
The best way in my opinion is to use the Array.forEach function. If you cannot use that I would suggest to get the polyfill from MDN. To make it available, it is certainly the safest way to iterate over an array in JavaScript.
Array.prototype.forEach()
So as others has suggested, this is almost always what you want:
This ensures that anything you need in the scope of processing the array stays within that scope, and that you are only processing the values of the array, not the object properties and other members, which is what
for ..
in does.Using a regular C-style
for
loop works in most cases. It is just important to remember that everything within the loop shares its scope with the rest of your program, the { } does not create a new scope.Hence:
will output "11" - which may or may not be what you want.
A working jsFiddle example:
https://jsfiddle.net/workingClassHacker/pxpv2dh5/7/
如果你想使用 jQuery,它的文档中有一个很好的例子:
If you want to use jQuery, it has a nice example in its documentation:
它不是 100% 相同,但相似:
It's not 100% identical, but similar:
例如,我在 Firefox 控制台中使用:
您可以使用 querySelectorAll 来获得相同的结果
For example, I used in a Firefox console:
You can use querySelectorAll to get same result
Opera、Safari、Firefox 和 Chrome 现在都共享一组增强的数组方法,用于优化许多常见循环。
您可能不需要全部,但它们可能非常有用,或者如果每个浏览器都支持它们,它们就会非常有用。
Mozilla Labs 发布了他们和 WebKit 都使用的算法,以便您可以自己添加它们。
过滤器返回满足某些条件或测试的项目数组。
如果每个数组成员都通过测试,every 返回 true。
如果有通过测试,some 返回 true。
forEach 对每个数组成员运行一个函数,并且不返回任何内容。
map 与 forEach 类似,但它返回每个元素的操作结果的数组。
这些方法都采用一个函数作为其第一个参数,并具有一个可选的第二个参数,该参数是一个对象,当数组成员循环遍历该函数时,您希望将其作用域施加到数组成员上。
忽略它直到你需要它。
indexOf 和 lastIndexOf 查找与其参数完全匹配的第一个或最后一个元素的适当位置。
Opera, Safari, Firefox and Chrome now all share a set of enhanced Array methods for optimizing many common loops.
You may not need all of them, but they can be very useful, or would be if every browser supported them.
Mozilla Labs published the algorithms they and WebKit both use, so that you can add them yourself.
filter returns an array of items that satisfy some condition or test.
every returns true if every array member passes the test.
some returns true if any pass the test.
forEach runs a function on each array member and doesn't return anything.
map is like forEach, but it returns an array of the results of the operation for each element.
These methods all take a function for their first argument and have an optional second argument, which is an object whose scope you want to impose on the array members as they loop through the function.
Ignore it until you need it.
indexOf and lastIndexOf find the appropriate position of the first or last element that matches its argument exactly.
简介
自上大学以来,我一直使用 Java、JavaScript、Pascal、ABAP、PHP 进行编程、Progress 4GL、C/C++ 以及可能还有一些我现在想不到的其他语言。
虽然它们都有自己的语言特质,但每种语言都有许多相同的基本概念。这些概念包括过程/函数、IF 语句、FOR 循环和 WHILE 循环。
传统的
for
循环传统的
for
循环包含三个组件:这三个组件是分开的彼此之间通过
;
符号。这三个组件的内容都是可选的,这意味着以下是可能的最小for
循环:当然,您需要包含一个
if(condition === true) { 休息; }
或if(condition === true) { return; }
位于for
循环内的某处以使其停止运行。不过,通常情况下,初始化用于声明索引,条件用于将该索引与最小值或最大值进行比较,事后用于增加索引:
使用传统的 for 循环循环遍历数组 循环
遍历数组的传统方法是这样的:
或者,如果您喜欢向后循环,则可以这样做:
但是,可能有许多变体,例如这个:
...或这个一个...
...或这个:
无论哪种效果最好,很大程度上取决于个人品味和您正在实施的具体用例。
请注意,所有浏览器都支持这些变体,包括非常非常旧的浏览器!
while
循环for
循环的一种替代方法是while
循环。要循环遍历数组,您可以这样做:与传统的
for
循环一样,while
循环甚至受到最古老的浏览器的支持。另请注意,每个 while 循环都可以重写为
for
循环。例如,上面的 while 循环的行为与 for 循环完全相同:For...in 和 for。 ..of
在 JavaScript 中,您也可以这样做:
但是,应谨慎使用,因为它在所有情况下的行为都与传统的
for
循环不同,并且需要考虑潜在的副作用。请参阅为什么使用“ for...in" 对于数组迭代是一个坏主意吗? 了解更多详细信息。作为
for...in
,现在还有for...of
。以下示例显示了for...of
循环和for...in
循环之间的区别:此外,您需要考虑没有任何版本的 Internet Explorer 支持
for...of
(Edge 12+ 确实),并且for...in
至少需要 Internet Explorer 10。Array.prototype.forEach()
for
-loops 的替代方案是Array.prototype.forEach()
,使用以下语法:<所有现代浏览器以及 Internet Explorer 9 及更高版本都支持 code>Array.prototype.forEach()。
库
最后,许多实用程序库也有自己的
foreach
变体。 AFAIK,最流行的三个是:jQuery.each()
,在 jQuery 中:_.each()
,位于 Underscore.js:<强>
_.forEach()
,在Lodash:Introduction
Since my time in college, I've programmed in Java, JavaScript, Pascal, ABAP, PHP, Progress 4GL, C/C++ and possibly a few other languages I can't think of right now.
While they all have their own linguistic idiosyncrasies, each of these languages share many of the same basic concepts. Such concepts include procedures / functions,
IF
-statements,FOR
-loops, andWHILE
-loops.A traditional
for
-loopA traditional
for
loop has three components:These three components are separated from each other by a
;
symbol. Content for each of these three components is optional, which means that the following is the most minimalfor
loop possible:Of course, you will need to include an
if(condition === true) { break; }
or anif(condition === true) { return; }
somewhere inside thatfor
-loop to get it to stop running.Usually, though, the initialization is used to declare an index, the condition is used to compare that index with a minimum or maximum value, and the afterthought is used to increment the index:
Using a traditional
for
loop to loop through an arrayThe traditional way to loop through an array, is this:
Or, if you prefer to loop backwards, you do this:
There are, however, many variations possible, like for example this one:
...or this one...
...or this one:
Whichever works best is largely a matter of both personal taste and the specific use case you're implementing.
Note that each of these variations is supported by all browsers, including very very old ones!
A
while
loopOne alternative to a
for
loop is awhile
loop. To loop through an array, you could do this:Like traditional
for
loops,while
loops are supported by even the oldest of browsers.Also, note that every while loop can be rewritten as a
for
loop. For example, thewhile
loop hereabove behaves the exact same way as thisfor
-loop:For...in
andfor...of
In JavaScript, you can also do this:
This should be used with care, however, as it doesn't behave the same as a traditional
for
loop in all cases, and there are potential side-effects that need to be considered. See Why is using "for...in" for array iteration a bad idea? for more details.As an alternative to
for...in
, there's now also forfor...of
. The following example shows the difference between afor...of
loop and afor...in
loop:Additionally, you need to consider that no version of Internet Explorer supports
for...of
(Edge 12+ does) and thatfor...in
requires at least Internet Explorer 10.Array.prototype.forEach()
An alternative to
for
-loops isArray.prototype.forEach()
, which uses the following syntax:Array.prototype.forEach()
is supported by all modern browsers, as well as Internet Explorer 9 and later.Libraries
Finally, many utility libraries also have their own
foreach
variation. AFAIK, the three most popular ones are these:jQuery.each()
, in jQuery:_.each()
, in Underscore.js:_.forEach()
, in Lodash:使用 while 循环...
它记录:“一”、“二”和“三”
对于相反的顺序,一个更高效的循环:
它记录:“三”、“二” ', 和 'one'
或者经典的
for
循环:它记录:'one','two','third'
参考:Google Closure:如何不编写 JavaScript
Use the while loop...
It logs: 'one', 'two', and 'three'
And for the reverse order, an even more efficient loop:
It logs: 'three', 'two', and 'one'
Or the classical
for
loop:It logs: 'one','two','three'
Reference: Google Closure: How not to write JavaScript
如果您想要一种简洁的方式来编写快速循环,您可以反向迭代:
这具有缓存长度的好处(类似于 for (var i=0, len=myArray. length; i 与
for (var i=0; i) 不同,但需要输入的字符较少。
甚至有时您应该反向迭代,例如迭代 实时 NodeList< /a> 您计划在迭代期间从 DOM 中删除项目。
If you want a terse way to write a fast loop and you can iterate in reverse:
This has the benefit of caching the length (similar to
for (var i=0, len=myArray.length; i<len; ++i)
and unlikefor (var i=0; i<myArray.length; ++i)
) while being fewer characters to type.There are even some times when you ought to iterate in reverse, such as when iterating over a live NodeList where you plan on removing items from the DOM during iteration.
JavaScript 中以函数式编程方式循环遍历数组的一些用例:
1. 仅循环遍历数组
注意:严格来说 Array.prototype.forEach() 并不是一种函数式方式,因为该函数它的输入参数不应该返回值,因此不能被视为纯函数。
2. 检查数组中的任何元素是否通过测试
3. 转换为新数组
注意:map() 方法创建一个新数组,其中包含对调用数组中的每个元素调用所提供函数的结果。
4. 对特定属性求和,并计算其平均值
5. 基于原始数组创建一个新数组,但不对其进行修改
6. 计算每个类别的数量
7. 根据特定条件检索数组的子集
注意:过滤器() 方法创建一个新数组,其中包含通过所提供函数实现的测试的所有元素。
8. 对数组进行排序
9. 在数组中查找元素
Array.prototype.find() 方法返回数组中满足所提供的第一个元素的值测试功能。
参考文献
Some use cases of looping through an array in the functional programming way in JavaScript:
1. Just loop through an array
Note: Array.prototype.forEach() is not a functional way strictly speaking, as the function it takes as the input parameter is not supposed to return a value, which thus cannot be regarded as a pure function.
2. Check if any of the elements in an array pass a test
3. Transform to a new array
Note: The map() method creates a new array with the results of calling a provided function on every element in the calling array.
4. Sum up a particular property, and calculate its average
5. Create a new array based on the original but without modifying it
6. Count the number of each category
7. Retrieve a subset of an array based on particular criteria
Note: The filter() method creates a new array with all elements that pass the test implemented by the provided function.
8. Sort an array
9. Find an element in an array
The Array.prototype.find() method returns the value of the first element in the array that satisfies the provided testing function.
References
是的,您可以在 JavaScript 中使用循环执行相同的操作,但不限于。在 JavaScript 中,有多种方法可以对数组进行循环。想象一下下面有这个数组,并且您想对其进行循环:
这些是解决方案:
1) For 循环
for
循环是一种常见的循环方式在 JavaScript 中通过数组,但它不被认为是大型数组最快的解决方案:2) While 循环
while 循环被认为是循环遍历长数组的最快方式,但通常较少使用在 JavaScript 代码中:
3) Do while
do while
与while
执行相同的操作,但有一些语法差异,如下所示:这些是执行 JavaScript 循环的主要方法,但还有其他几种方法可以执行那。
我们还使用
for in
循环来循环 JavaScript 中的对象。另请查看 JavaScript 中数组上的
map()
、filter()
、reduce()
等函数。它们可能比使用while
和for
做得更快更好。如果您想了解有关 JavaScript 中数组的异步函数的更多信息,这是一篇很好的文章。
了解更多>> 此处:
Yes, you can do the same in JavaScript using a loop, but not limited to that. There are many ways to do a loop over arrays in JavaScript. Imagine you have this array below, and you'd like to do a loop over it:
These are the solutions:
1) For loop
A
for
loop is a common way looping through arrays in JavaScript, but it is no considered as the fastest solutions for large arrays:2) While loop
A while loop is considered as the fastest way to loop through long arrays, but it is usually less used in the JavaScript code:
3) Do while
A
do while
is doing the same thing aswhile
with some syntax difference as below:These are the main ways to do JavaScript loops, but there are a few more ways to do that.
Also we use a
for in
loop for looping over objects in JavaScript.Also look at the
map()
,filter()
,reduce()
, etc. functions on an Array in JavaScript. They may do things much faster and better than usingwhile
andfor
.This is a good article if you like to learn more about the asynchronous functions over arrays in JavaScript.
Read more>> here:
有一种方法可以做到这一点,即循环中的隐式作用域非常小,并且不需要额外的变量。
或者,如果您确实想获取 id 并拥有一个非常经典的
for
循环:现代浏览器都支持迭代器方法
forEach
、map
、reduce
、filter
以及 数组原型。There is a way to do it where you have very little implicit scope in your loop and do away with extra variables.
Or if you really want to get the id and have a really classical
for
loop:Modern browsers all support iterator methods
forEach
,map
,reduce
,filter
and a host of other methods on the Array prototype.JavaScript 中有多种循环数组的方法。
通用循环:
ES5 的 forEach:
jQuery.each:
看看 此了解详细信息,或者您也可以查看MDN 用于在 JavaScript 和 JavaScript 中循环遍历数组使用 jQuery 检查 每个 jQuery。
There are various way to loop through array in JavaScript.
Generic loop:
ES5's forEach:
jQuery.each:
Have a look this for detailed information or you can also check MDN for looping through an array in JavaScript & using jQuery check jQuery for each.
数组循环:
对象循环:
Array loop:
Object loop:
我强烈建议使用 Underscore.js 库。它为您提供了各种可用于迭代数组/集合的函数。
例如:
I would thoroughly recommend making use of the Underscore.js library. It provides you with various functions that you can use to iterate over arrays/collections.
For instance:
如果有人对可用于数组迭代的多种机制的性能方面感兴趣,我准备了以下 JSPerf 测试:
https://jsperf.com/fastest-array-iterator
结果:
传统的
for()
迭代器是迄今为止最快的方法,尤其是与缓存的数组长度。Array.prototype.forEach()
和Array.prototype.map()
方法是最慢的近似方法,可能是由于函数调用开销< /强>。If anybody is interested in the performance side of the multiple mechanisms available for Array iterations, I've prepared the following JSPerf tests:
https://jsperf.com/fastest-array-iterator
Results:
The traditional
for()
iterator, is by far the fastest method, especially when used with the array length cached.The
Array.prototype.forEach()
and theArray.prototype.map()
methods are the slowest approximations, probably as a consequence of the function call overhead.如果您使用 jQuery 库,请考虑使用
http://api.jquery.com/jQuery.each/
从文档中:
If you're using the jQuery library, consider using
http://api.jquery.com/jQuery.each/
From the documentation:
我还没有看到这种变化,我个人最喜欢它:
给定一个数组:
您可以循环它而无需访问 length 属性:
请参阅此 JsFiddle 演示: http://jsfiddle.net/prvzk/
这仅适用于不稀疏的数组。这意味着数组中的每个索引实际上都有一个值。然而,我发现实际上我很少在 JavaScript 中使用稀疏数组......在这种情况下,使用对象作为映射/哈希表通常要容易得多。如果您确实有一个稀疏数组,并且想要循环 0 .. length-1,则需要 for (var i=0; i if 在循环内检查当前索引处的元素是否实际定义。
另外,正如 CMS 在下面的评论中提到的,您只能在不包含任何虚假值的数组上使用它。示例中的字符串数组可以工作,但如果有空字符串、0 或 NaN 等数字,则循环将提前中断。同样,在实践中,这对我来说几乎不是问题,但需要记住这一点,这使得在使用它之前需要考虑一个循环......这可能会取消某些人的资格:)
我喜欢这个的原因循环是:
身体在您选择的名字下。
这样做的原因是数组规范要求当您从索引 >= 数组长度读取项目时,它将返回 undefined。当您写入这样的位置时,它实际上会更新长度。
对我来说,这个构造最接近地模拟了我喜欢的 Java 5 语法:
...还有一个额外的好处,就是还可以了解循环内的当前索引
I did not yet see this variation, which I personally like the best:
Given an array:
You can loop over it without ever accessing the length property:
See this JsFiddle demonstrating that: http://jsfiddle.net/prvzk/
This only works for arrays that are not sparse. Meaning that there actually is a value at each index in the array. However, I found that in practice I hardly ever use sparse arrays in JavaScript... In such cases it's usually a lot easier to use an object as a map/hashtable. If you do have a sparse array, and want to loop over 0 .. length-1, you need the for (var i=0; i<someArray.length; ++i) construct, but you still need an
if
inside the loop to check whether the element at the current index is actually defined.Also, as CMS mentions in a comment below, you can only use this on arrays that don't contain any falsish values. The array of strings from the example works, but if you have empty strings, or numbers that are 0 or NaN, etc. the loop will break off prematurely. Again in practice this is hardly ever a problem for me, but it is something to keep in mind, which makes this a loop to think about before you use it... That may disqualify it for some people :)
What I like about this loop is:
body under the name you pick.
The reason this works is that the array specification mandates that when you read an item from an index >= the array's length, it will return undefined. When you write to such a location it will actually update the length.
For me, this construct most closely emulates the Java 5 syntax that I love:
... with the added benefit of also knowing about the current index inside the loop
数组迭代有 4 种方式:
摘要:1 和 3 解决方案创建额外的变量,2 - 创建额外的函数上下文。 最好的方法是第四种 - “for of”。
There are 4 ways of array iteration:
Summary: 1 and 3 solutions create extra variable, 2 - create extra function context. The best way is 4th - "for of".
深奥的
性能测试
今天(2022-11-13)我在 Chrome 107、Safari 15.2 和 Firefox 106 上对所选解决方案进行了测试。
结论
结果
详细信息
我执行 3 个测试:
下面的代码片段展示了测试中使用的代码。
以下是 Chrome 对于中等数组的结果示例:
Esoteric
Performance test
Today (2022-11-13) I perform a test on Chrome 107, Safari 15.2 and Firefox 106 on chosen solutions.
Conclusions
Results
Details
I perform 3 tests:
The below snippet presents code used in the test.
Here are example results for Chrome for a medium array:
有一种方法可以只迭代自己的对象属性,不包括原型的属性:
但它仍然会迭代自定义属性。
在 JavaScript 中,任何自定义属性都可以分配给任何对象,包括数组。
如果想要迭代稀疏数组,
for (var i = 0; i < array.length; i++) if (i in array)
或array.forEach
with应使用es5shim
。There's a method to iterate over only own object properties, not including prototype's ones:
but it still will iterate over custom-defined properties.
In JavaScript any custom property could be assigned to any object, including an array.
If one wants to iterate over sparsed array,
for (var i = 0; i < array.length; i++) if (i in array)
orarray.forEach
withes5shim
should be used.最优雅、最快速的方式
http://jsperf.com/native-loop-performance/8
已编辑(因为我错了)
比较循环遍历 100000 个项目的数组的方法,并每次对新值执行最小操作。
准备:
测试:
The most elegant and fast way
http://jsperf.com/native-loop-performance/8
Edited (because I was wrong)
Comparing methods for looping through an array of 100000 items and do a minimal operation with the new value each time.
Preparation:
Tests:
在 JavaScript 中,有几种方法可以做到这一点。前两个示例是 JavaScript 示例。第三种使用 JavaScript 库,即 jQuery 使用
.each()
函数。There are a couple of ways to do it in JavaScript. The first two examples are JavaScript samples. The third one makes use of a JavaScript library, that is, jQuery making use of the
.each()
function.优化的方法是缓存数组的长度并使用单变量模式,使用单个
var
关键字初始化所有变量。如果迭代的顺序并不重要,那么您应该尝试反向循环。它是最快的,因为它减少了条件测试的开销,并且减量在一个语句中:
或者使用 while 循环更好、更干净:
The optimized approach is to cache the length of array and using the single variable pattern, initializing all variables with a single
var
keyword.If the order of iteration does not matter then you should try reversed loop. It is the fastest as it reduces overhead condition testing and decrement is in one statement:
Or better and cleaner to use a while loop:
在 JavaScript 中,有很多循环数组的解决方案。
下面的代码是流行的
In JavaScript, there are so many solutions to loop an array.
The code below are popular ones
三个主要选项:
xs.forEach((x, i) => console.log(x));
for (const x of xs) { console.log(x); }
详细示例如下。
1. 顺序
for
循环:优点
break
和continue
流程控制语句缺点
2.
Array.prototype.forEach
:ES5 规范引入了很多有益的数组方法。其中之一是
Array.prototype .forEach
为我们提供了一种迭代数组的简洁方法:ES5 规范发布(2009 年 12 月)已近十年,它已被桌面、服务器和移动环境中的几乎所有现代引擎实现,因此使用它们是安全的。
使用 ES6 箭头函数语法,它更加简洁:
箭头函数也被广泛实现,除非您计划支持古老的平台(例如,Internet Explorer 11);你也可以安全离开了。
优点
缺点
break
/continue
通常,您可以通过过滤来代替
break
脱离命令式循环的需要迭代数组元素之前,例如:请记住,如果您要迭代数组以从中构建另一个数组,则应使用
map
。我已经多次看到这种反模式。反模式:
地图的正确用例:
另外,如果您尝试将数组减少为一个值,例如,您想要对数字数组求和,则应该使用reduce方法。
反模式:
正确使用reduce:
3. ES6
for-of
语句:ES6 标准引入了可迭代对象的概念,并定义了一种用于遍历数据的新结构,即
for...of
语句。此语句适用于任何类型的可迭代对象,也适用于生成器(任何具有
\[Symbol.iterator\]
属性)。根据定义,数组对象是 ES6 中内置的可迭代对象,因此您可以对它们使用以下语句:
优点
break
/continue
)。缺点
不要使用
for...in
@zipcodeman 建议使用
for...in
语句,但用于迭代数组for-in
应避免,该语句旨在枚举对象属性。它不应该用于类似数组的对象,因为:
第二点是它会给你带来很多问题,例如,如果你扩展 Array.prototype 对象以包含其中的方法,那么该属性也将被枚举。
例如:
上面的代码将控制台日志“a”、“b”、“c”和“foo!”。
如果您使用一些严重依赖本机原型增强的库(例如 MooTools)。
正如我之前所说,for-in 语句是用来枚举对象属性的,例如:
在上面的示例中,
hasOwnProperty
方法允许您仅枚举自己的属性。就是这样,只有对象物理上具有的属性,没有继承的属性。我建议您阅读以下文章:
Three main options:
for (var i = 0; i < xs.length; i++) { console.log(xs[i]); }
xs.forEach((x, i) => console.log(x));
for (const x of xs) { console.log(x); }
Detailed examples are below.
1. Sequential
for
loop:Pros
break
andcontinue
flow control statementsCons
2.
Array.prototype.forEach
:The ES5 specification introduced a lot of beneficial array methods. One of them, the
Array.prototype.forEach
, gave us a concise way to iterate over an array:Being almost ten years as the time of writing that the ES5 specification was released (Dec. 2009), it has been implemented by nearly all modern engines in the desktop, server, and mobile environments, so it's safe to use them.
And with the ES6 arrow function syntax, it's even more succinct:
Arrow functions are also widely implemented unless you plan to support ancient platforms (e.g., Internet Explorer 11); you are also safe to go.
Pros
Cons
break
/continue
Normally, you can replace the need to
break
out of imperative loops by filtering the array elements before iterating them, for example:Keep in mind if you are iterating an array to build another array from it, you should use
map
. I've seen this anti-pattern so many times.Anti-pattern:
Proper use case of map:
Also, if you are trying to reduce the array to a value, for example, you want to sum an array of numbers, you should use the reduce method.
Anti-pattern:
Proper use of reduce:
3. ES6
for-of
statement:The ES6 standard introduces the concept of iterable objects and defines a new construct for traversing data, the
for...of
statement.This statement works for any kind of iterable object and also for generators (any object that has a
\[Symbol.iterator\]
property).Array objects are by definition built-in iterables in ES6, so you can use this statement on them:
Pros
break
/continue
).Cons
Do not use
for...in
@zipcodeman suggests the use of the
for...in
statement, but for iterating arraysfor-in
should be avoided, that statement is meant to enumerate object properties.It shouldn't be used for array-like objects because:
The second point is that it can give you a lot of problems, for example, if you extend the
Array.prototype
object to include a method there, that property will also be enumerated.For example:
The above code will console log "a", "b", "c", and "foo!".
That can be particularly a problem if you use some library that relies heavily on native prototypes augmentation (such as MooTools).
The
for-in
statement, as I said before, is there to enumerate object properties, for example:In the above example, the
hasOwnProperty
method allows you to enumerate only own properties. That's it, only the properties that the object physically has, no inherited properties.I would recommend you to read the following article:
是的,假设您的实施包括
for
...of
ECMAScript 2015(“Harmony”版本)……目前这是一个相当安全的假设。它的工作原理如下:
或者更好,因为 ECMAScript 2015 还提供了块作用域变量:(
变量
s
在每次迭代中都不同,但仍然可以在内部声明const
关于稀疏数组的注意事项:JavaScript 中的数组实际上可能不会存储与其
length
报告的一样多的项目;该数字仅比存储值的最高索引大 1。如果数组包含的元素少于其长度所指示的元素,则称其为稀疏。例如,拥有一个仅包含索引 3、12 和 247 处的项目的数组是完全合法的;这样一个数组的长度是 248,尽管它实际上只存储 3 个值。如果您尝试访问任何其他索引处的项目,该数组将显示为具有undefined
值,但该数组仍然与实际具有undefined
的数组不同存储的值。您可以通过多种方式看到这种差异,例如 Node REPL 显示数组的方式:因此,当您想要“循环”数组时,您需要回答一个问题:您想要循环整个范围吗?由其长度指示并处理任何缺失元素的
undefined
,或者您只想处理实际存在的元素?这两种方法都有很多应用;这仅取决于您使用数组的目的。如果使用
for
..of
迭代数组,则循环体将执行length
次,并设置循环控制变量对于数组中实际不存在的任何项目,将其设置为undefined
。根据“使用”代码的详细信息,该行为可能是您想要的,但如果不是,您应该使用不同的方法。当然,一些开发人员别无选择,只能使用不同的方法,因为无论出于何种原因,他们的目标 JavaScript 版本尚不支持
for
...of< /代码>。
只要您的 JavaScript 实现符合 ECMAScript 规范的上一版本(例如,排除了 Internet Explorer 9 之前的版本),那么您就可以使用
Array#forEach
迭代器方法而不是一个循环。在这种情况下,您传递一个要在数组中的每个项目上调用的函数:如果您的实现支持 ES6+,您当然可以使用箭头函数:
与
for
...of,
.forEach
仅针对数组中实际存在的元素调用该函数。如果传递我们假设的包含三个元素且长度为 248 的数组,它只会调用该函数 3 次,而不是 248 次。如果这就是您想要处理稀疏数组的方式,即使您的解释器支持for
...of
,.forEach
也可能是可行的方法。最后一个选项是 所有版本的 JavaScript rel="noreferrer">显式计数循环。您只需从 0 计数到比长度少 1 并使用计数器作为索引即可。基本循环如下所示:
这种方法的一个优点是您可以选择如何处理稀疏数组。上面的代码将运行循环体完整的
length
次,对于任何缺失的元素,将s
设置为undefined
,就像>for
..of
;如果您只想处理稀疏数组中实际存在的元素,例如.forEach
,您可以在索引上添加一个简单的in
测试:具体取决于您的实现优化时,将长度值分配给局部变量(而不是在循环条件中包含完整的
myStringArray.length
表达式)可以显着提高性能,因为它每次都会跳过属性查找。您可能会看到在循环初始化子句中完成的长度缓存,如下所示:显式计数循环还意味着您可以访问每个值的索引(如果您需要的话)。索引还会作为额外参数传递给您传递给
forEach
的函数,因此您也可以通过这种方式访问它:for
...of< /code> 不会为您提供与每个对象关联的索引,但只要您要迭代的对象实际上是
Array
的实例(而不是其他可迭代类型之一for
..of
有效),您可以使用 Array#entries 方法将其更改为 [index, item] 对的数组,然后对其进行迭代:for
...in
其他人提到的语法用于循环对象的属性;由于 JavaScript 中的数组只是一个具有数字属性名称的对象(以及自动更新的length
属性),因此理论上您可以使用它循环遍历数组。但问题是它并不将自己限制为数字属性值(请记住,即使是方法实际上也只是其值为闭包的属性),也不保证按数字顺序迭代这些属性。因此,for
...in
语法不应该用于循环数组。Yes, assuming your implementation includes the
for
...of
feature introduced in ECMAScript 2015 (the "Harmony" release)... which is a pretty safe assumption these days.It works like this:
Or better yet, since ECMAScript 2015 also provides block-scoped variables:
(The variable
s
is different on each iteration, but can still be declaredconst
inside the loop body as long as it isn't modified there.)A note on sparse arrays: an array in JavaScript may not actually store as many items as reported by its
length
; that number is simply one greater than the highest index at which a value is stored. If the array holds fewer elements than indicated by its length, its said to be sparse. For example, it's perfectly legitimate to have an array with items only at indexes 3, 12, and 247; thelength
of such an array is 248, though it is only actually storing 3 values. If you try to access an item at any other index, the array will appear to have theundefined
value there, but the array is nonetheless is distinct from one that actually hasundefined
values stored. You can see this difference in a number of ways, for example in the way the Node REPL displays arrays:So when you want to "loop through" an array, you have a question to answer: do you want to loop over the full range indicated by its length and process
undefined
s for any missing elements, or do you only want to process the elements actually present? There are plenty of applications for both approaches; it just depends on what you're using the array for.If you iterate over an array with
for
..of
, the body of the loop is executedlength
times, and the loop control variable is set toundefined
for any items not actually present in the array. Depending on the details of your "do something with" code, that behavior may be what you want, but if not, you should use a different approach.Of course, some developers have no choice but to use a different approach anyway, because for whatever reason they're targeting a version of JavaScript that doesn't yet support
for
...of
.As long as your JavaScript implementation is compliant with the previous edition of the ECMAScript specification (which rules out, for example, versions of Internet Explorer before 9), then you can use the
Array#forEach
iterator method instead of a loop. In that case, you pass a function to be called on each item in the array:You can of course use an arrow function if your implementation supports ES6+:
Unlike
for
...of
,.forEach
only calls the function for elements that are actually present in the array. If passed our hypothetical array with three elements and a length of 248, it will only call the function three times, not 248 times. If this is how you want to handle sparse arrays,.forEach
may be the way to go even if your interpreter supportsfor
...of
.The final option, which works in all versions of JavaScript, is an explicit counting loop. You simply count from 0 up to one less than the length and use the counter as an index. The basic loop looks like this:
One advantage of this approach is that you can choose how to handle sparse arrays. The above code will run the body of the loop the full
length
times, withs
set toundefined
for any missing elements, just likefor
..of
; if you instead want to handle only the actually-present elements of a sparse array, like.forEach
, you can add a simplein
test on the index:Depending on your implementation's optimizations, assigning the length value to the local variable (as opposed to including the full
myStringArray.length
expression in the loop condition) can make a significant difference in performance since it skips a property lookup each time through. You may see the length caching done in the loop initialization clause, like this:The explicit counting loop also means you have access to the index of each value, should you want it. The index is also passed as an extra parameter to the function you pass to
forEach
, so you can access it that way as well:for
...of
doesn't give you the index associated with each object, but as long as the object you're iterating over is actually an instance ofArray
(and not one of the other iterable typesfor
..of
works on), you can use the Array#entries method to change it to an array of [index, item] pairs, and then iterate over that:The
for
...in
syntax mentioned by others is for looping over an object's properties; since an Array in JavaScript is just an object with numeric property names (and an automatically-updatedlength
property), you can theoretically loop over an Array with it. But the problem is that it doesn't restrict itself to the numeric property values (remember that even methods are actually just properties whose value is a closure), nor is it guaranteed to iterate over those in numeric order. Therefore, thefor
...in
syntax should not be used for looping through Arrays.您可以使用
map
,这是一种函数式编程技术,也可用于其他语言,例如 Python 和 Haskell。一般语法是:
一般来说,
func
将采用一个参数,该参数是数组的一项。但就 JavaScript 而言,它可以采用第二个参数(即项目的索引)和第三个参数(即数组本身)。array.map
的返回值是另一个数组,因此您可以像这样使用它:现在 x 是
[10,20,30,40]
。您不必内联编写该函数。它可以是一个单独的函数。
这有点相当于:
除非你没有得到
new_list
。You can use
map
, which is a functional programming technique that's also available in other languages like Python and Haskell.The general syntax is:
In general
func
would take one parameter, which is an item of the array. But in the case of JavaScript, it can take a second parameter which is the item's index, and a third parameter which is the array itself.The return value of
array.map
is another array, so you can use it like this:And now x is
[10,20,30,40]
.You don't have to write the function inline. It could be a separate function.
which would be sort-of equivalent to:
Except you don't get the
new_list
.for (const s of myStringArray) {
(直接回答你的问题:现在你可以了!)
大多数其他答案都是正确的,但他们没有提到(截至撰写本文时)ECMAScript
6 ;2015 引入了一种新的迭代机制,即for..of
循环。这种新语法是在 JavaScript 中迭代数组的最优雅的方法(只要不需要迭代索引)。
目前它适用于 Firefox 13+、Chrome 37+,并且本身不支持其他浏览器(请参阅下面的浏览器兼容性)。幸运的是,我们拥有 JavaScript 编译器(例如 Babel),使我们能够使用当今的下一代功能。
它也适用于 Node.js(我在 0.12.0 版本上测试过)。
迭代数组
迭代对象数组
迭代生成器:
(示例摘自https://developer.mozilla.org/en-US/docs/Web/ JavaScript/Reference/Statements/for...of)
兼容性表:
http://kangax.github.io/compat-table/ es6/#test-for..of_loops
规范: http://wiki.ecmascript.org/doku.php?id=harmony:iterators
}
for (const s of myStringArray) {
(Directly answering your question: now you can!)
Most other answers are right, but they do not mention (as of this writing) that ECMAScript
62015 is bringing a new mechanism for doing iteration, thefor..of
loop.This new syntax is the most elegant way to iterate an array in JavaScript (as long you don't need the iteration index).
It currently works with Firefox 13+, Chrome 37+ and it does not natively work with other browsers (see browser compatibility below). Luckily we have JavaScript compilers (such as Babel) that allow us to use next-generation features today.
It also works on Node.js (I tested it on version 0.12.0).
Iterating an array
Iterating an array of objects
Iterating a generator:
(example extracted from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of)
Compatibility table:
http://kangax.github.io/compat-table/es6/#test-for..of_loops
Specification: http://wiki.ecmascript.org/doku.php?id=harmony:iterators
}
在 JavaScript 中,不建议使用 for-in 循环遍历数组,但最好使用
for
循环,例如:它也经过优化(“缓存”数组长度)。如果您想了解更多信息,阅读我关于该主题的帖子。
In JavaScript it's not advisable to loop through an Array with a for-in loop, but it's better to use a
for
loop such as:It's optimized as well ("caching" the array length). If you'd like to learn more, read my post on the subject.
循环数组的 6 种不同方法
您可以通过多种不同的方法循环数组。我从上到下对我最喜欢的 6 种方法进行了排序。
1. 使用 JavaScript for 循环
当只是简单地循环遍历数组时,
for
循环是我的第一选择。2. 使用 forEach 循环
forEach
循环是一种循环遍历数组的现代方法。此外,它还提供了对数组和元素的更大灵活性和控制。3. 使用 for...of
for...of
循环可以让您直接访问数组元素。4. 使用 for...in 循环
for...in
为您提供一个可以访问数组元素的键。5. 使用while 循环
while 循环也可用于循环数组。
6. 使用 do...while 循环
同样,我使用
do...while
循环6 different methods to loop through the array
You can loop through an array by many different methods. I have sorted my 6 favorite methods from top to bottom.
1. Using JavaScript for loop
When it's to simply loop through an array, the
for
loop is my first choice.2. Using forEach loop
forEach
loop is a modern way to loop through the array. Also, it gives more flexibility and control over the array and elements.3. Using for...of
for...of
loop gives you direct access to the array elements.4. Using for...in loop
for...in
gives you a key using which you can access array elements.5. Using while loop
while loop is can be used to loop through the array as well.
6. Using do...while loop
Likewise, I use
do...while
loop