In Java you can use a for
loop to traverse objects in an array as follows:
在Java中,可以使用for循环遍历数组中的对象:
String[] myStringArray = {"Hello", "World"};
for (String s : myStringArray)
{
// Do something
}
Can you do the same in JavaScript?
你能用JavaScript做同样的事情吗?
35 个解决方案
#1
2943
Use a sequential for
loop:
使用顺序for循环:
var myStringArray = ["Hello","World"];
var arrayLength = myStringArray.length;
for (var i = 0; i < arrayLength; i++) {
alert(myStringArray[i]);
//Do something
}
@zipcodeman suggests the use of the for...in
statement, but for iterating arrays for-in
should be avoided, that statement is meant to enumerate object properties.
@zipcodeman建议使用for…在语句中,但要避免迭代数组,该语句的目的是枚举对象属性。
It shouldn't be used for array-like objects because:
它不应该用于arraylike对象,因为:
- The order of iteration is not guaranteed, the array indexes may not be visited in numeric order.
- 迭代的顺序没有保证,数组索引可能不会以数字顺序访问。
- Inherited properties are also enumerated.
- 继承的属性也被枚举。
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 be also enumerated.
第二点是它可以给你很多问题,例如,如果你扩展数组。原型对象中包含一个方法,该属性也将被枚举。
For example:
例如:
Array.prototype.foo = "foo!";
var array = ['a', 'b', 'c'];
for (var i in array) {
alert(array[i]);
}
The above code will alert, "a", "b", "c" and "foo!".
上面的代码会提示,“a”,“b”,“c”和“foo!”
That be particularly a problem if you use some library that relies heavily on native prototypes augmention (such as MooTools for example).
如果您使用大量依赖本机原型的库(例如MooTools),那么这将是一个特别的问题。
The for-in
statement as I said before is there to enumerate object properties, for example:
我之前说过的forin语句是用来枚举对象属性的,例如:
var obj = {
"a": 1,
"b": 2,
"c": 3
};
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
// or if (Object.prototype.hasOwnProperty.call(obj,prop)) for safety...
alert("prop: " + prop + " value: " + obj[prop])
}
}
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.
在上面的例子中,hasOwnProperty方法允许您只枚举自己的属性,也就是它,只是对象物理上拥有的属性,没有继承属性。
I would recommend you to read the following article:
我建议您阅读以下文章:
- Enumeration VS Iteration
- 枚举和迭代
#2
795
Yes, but only if your implementation includes the for
...of
feature introduced in ECMAScript 2015 (the "Harmony" release).
是的,但前提是你的实现包括……2015年ECMAScript(“和谐”版本)中引入的功能。
It works like this:
是这样的:
// REQUIRES ECMASCRIPT 2015+
var s, myStringArray = ["Hello", "World"];
for (s of myStringArray) {
// ... do something with s ...
}
Or better yet, since ECMAScript 2015 also provides block-scoped variables via let
and const
:
或者更好,因为ECMAScript 2015还通过let和const提供了块范围的变量:
// REQUIRES ECMASCRIPT 2015+
const myStringArray = ["Hello", "World"];
for (let s of myStringArray) {
// ... do something with s ...
}
// s is no longer defined here
Many JavaScript developers are still working in an environment that's not there yet, however - especially if writing code to run in web browsers, where the site developers often can't be sure what browser/version their clients will be using.
许多JavaScript开发人员仍然在一个尚未开发的环境中工作——特别是如果在web浏览器中编写代码,站点开发人员常常无法确定他们的客户将使用什么浏览器/版本。
If you can assume the JavaScript interpreter 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 forEach
iterator method instead of a loop. In that case, you pass a function to be called on each item in the array:
如果您可以假设JavaScript解释器符合ECMAScript规范的前一个版本(例如,在9之前就排除了Internet Explorer的版本),那么您可以使用forEach迭代器方法而不是一个循环。在这种情况下,您传递一个函数来调用数组中的每个项:
var myStringArray = [ "Hello", "World" ];
myStringArray.forEach( function(s) {
// ... do something with s ...
} );
But if even that is too much to assume, and you want something that works in all versions of JavaScript, then you have to use an explicit counting loop. The safest version, which handles sparse arrays properly, is something like this:
但是,如果这是太多的假设,并且您希望在所有的JavaScript版本中都有工作,那么您必须使用一个显式计数循环。最安全的处理稀疏数组的版本是这样的:
var i, s, myStringArray = [ "Hello", "World" ], len = myStringArray.length;
for (i=0; i<len; ++i) {
if (i in myStringArray) {
s = myStringArray[i];
// ... do something with s ...
}
}
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; using Rhino on my machine, the speedup is 43%.
将长度值分配给局部变量(而不是包括完整的myStringArray)。在循环条件下的长度表达式)可以在性能上产生显著的差异,因为它每次都跳过属性查找;在我的机器上使用Rhino,加速率为43%。
You will often see the length caching done in the loop initialization clause, like this:
您将经常看到在循环初始化子句中完成的长度缓存:
var i, len, myStringArray = [ "Hello", "World" ];
for (len = myStringArray.length, i=0; i<len; ++i) {
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-updated length
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 does it iterate over those in numeric order. Therefore, the for
...in
syntax should not be used for looping through Arrays.
为…在语法中,别人提到的是对对象的属性进行循环;由于JavaScript中的数组只是一个具有数字属性名的对象(以及一个自动更新的长度属性),所以理论上可以对数组进行循环。但问题是,它并不局限于数字属性值(请记住,即使方法实际上只是值为闭包的属性),也不会对那些数字顺序进行迭代。因此,……在语法中不应该用于遍历数组。
#3
383
You can use map
, which is a functional programming technique that's also available in other languages like Python and Haskell.
您可以使用map,这是一种函数式编程技术,也可以使用其他语言,如Python和Haskell。
[1,2,3,4].map( function(item) {
alert(item);
})
The general syntax is:
一般的语法是:
array.map(func)
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.
一般来说,func会取一个参数,它是数组的一个项。但是在JavaScript的情况下,它可以使用第二个参数,它是项的索引,第三个参数是数组本身。
The return value of array.map
is another array, so you can use it like this:
数组的返回值。map是另一个数组,所以可以这样使用:
var x = [1,2,3,4].map( function(item) {return item * 10;});
And now x is [10,20,30,40]
.
现在x是(10,20,30,40)
You don't have to write the function inline. It could be a separate function.
你不需要内联写函数。它可以是一个单独的函数。
var item_processor = function(item) {
// Do something complicated to an item
}
new_list = my_list.map(item_processor);
which would be sort-of equivalent to:
这相当于:
for (item in my_list) {item_processor(item);}
Except you don't get the new_list
.
除非你没有得到new_list。
#4
97
In JavaScript it's not advisable to loop through an Array with a for-in loop, but it's better using a for loop such as:
在JavaScript中,用forin循环遍历数组是不明智的,但是最好使用for循环,例如:
for(var i=0, len=myArray.length; i < len; i++){}
It's optimized as well ("caching" the array length). If you'd like to learn more, read my post on the subject.
它也进行了优化(“缓存”数组长度)。如果你想了解更多,请阅读我关于这个主题的文章。
#5
89
for (var 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 ECMA Script
6
2015 is bringing a new mechanism for doing iteration, the for..of
loop.
大多数其他的答案都是正确的,但是他们没有提到ECMA脚本6 2015正在为迭代开发提供一种新的机制。的循环。
This new syntax is the most elegant way to iterate an array in javascript (as long you don't need the iteration index), but it is not yet widely supported by the browsers.
这种新语法是在javascript中迭代数组的最优雅的方法(因为您不需要迭代索引),但是它还没有得到浏览器的广泛支持。
It currently works with Firefox 13+, Chrome 37+ and it does not natively work with other browsers (see browser compatibility below). Luckily we have JS compilers (such as Babel) that allow us to use next-generation features today.
它目前使用的是Firefox 13+, Chrome 37+,而且它并没有与其他浏览器一起使用(参见下面的浏览器兼容性)。幸运的是,我们有JS编译器(比如Babel),它允许我们今天使用下一代功能。
It also works on Node (I tested it on version 0.12.0).
它也适用于Node(我在0.12.0版上测试过)。
Iterating an array
遍历一个数组
// You could also use "let" instead of "var" for block scope.
for (var letter of ["a", "b", "c"]) {
console.log(letter);
}
Iterating an array of objects
迭代对象数组。
var band = [
{firstName : 'John', lastName: 'Lennon'},
{firstName : 'Paul', lastName: 'McCartney'}
];
for(var member of band){
console.log(member.firstName + ' ' + member.lastName);
}
Iterating a generator:
迭代一个发电机:
(example extracted from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of)
(例如从https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of)中提取
function* fibonacci() { // a generator function
let [prev, curr] = [1, 1];
while (true) {
[prev, curr] = [curr, prev + curr];
yield curr;
}
}
for (let n of fibonacci()) {
console.log(n);
// truncate the sequence at 1000
if (n >= 1000) {
break;
}
}
Compatibility table: http://kangax.github.io/es5-compat-table/es6/#For..of loops
兼容性表:http://kangax.github.io/es5-compat-table/es6/ . .的循环
Spec: http://wiki.ecmascript.org/doku.php?id=harmony:iterators
规范:http://wiki.ecmascript.org/doku.php?id=harmony:迭代器
}
#6
80
Opera, Safari, Firefox and Chrome now all share a set of enhanced Array methods for optimizing many common loops.
Opera、Safari、Firefox和Chrome现在都共享一组增强的数组方法来优化许多常见的循环。
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.
Mozilla实验室发布了他们和WebKit都使用的算法,这样你就可以自己添加它们了。
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.
如果通过测试,一些返回true。
forEach runs a function on each array member and doesn't return anything.
forEach在每个数组成员上运行一个函数,并没有返回任何值。
map is like forEach, but it returns an array of the results of the operation for each element.
map就像forEach,但它返回每个元素的操作结果的数组。
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.
indexOf和lastIndexOf找到匹配其参数的第一个或最后一个元素的适当位置。
(function(){
var p, ap= Array.prototype, p2={
filter: function(fun, scope){
var L= this.length, A= [], i= 0, val;
if(typeof fun== 'function'){
while(i< L){
if(i in this){
val= this[i];
if(fun.call(scope, val, i, this)){
A[A.length]= val;
}
}
++i;
}
}
return A;
},
every: function(fun, scope){
var L= this.length, i= 0;
if(typeof fun== 'function'){
while(i<L){
if(i in this && !fun.call(scope, this[i], i, this))
return false;
++i;
}
return true;
}
return null;
},
forEach: function(fun, scope){
var L= this.length, i= 0;
if(typeof fun== 'function'){
while(i< L){
if(i in this){
fun.call(scope, this[i], i, this);
}
++i;
}
}
return this;
},
indexOf: function(what, i){
i= i || 0;
var L= this.length;
while(i< L){
if(this[i]=== what)
return i;
++i;
}
return -1;
},
lastIndexOf: function(what, i){
var L= this.length;
i= i || L-1;
if(isNaN(i) || i>= L)
i= L-1;
else
if(i< 0) i += L;
while(i> -1){
if(this[i]=== what)
return i;
--i;
}
return -1;
},
map: function(fun, scope){
var L= this.length, A= Array(this.length), i= 0, val;
if(typeof fun== 'function'){
while(i< L){
if(i in this){
A[i]= fun.call(scope, this[i], i, this);
}
++i;
}
return A;
}
},
some: function(fun, scope){
var i= 0, L= this.length;
if(typeof fun== 'function'){
while(i<L){
if(i in this && fun.call(scope, this[i], i, this))
return true;
++i;
}
return false;
}
}
}
for(p in p2){
if(!ap[p])
ap[p]= p2[p];
}
return true;
})();
#7
62
Use the while loop...
使用while循环……
var i=0, item, items = ['one','two','three'];
while(item = items[i++]){
console.log(item);
}
logs: 'one','two','three'
日志:“1”,“2”,“3”
And for the reverse order, an even more efficient loop
对于相反的顺序,一个更有效的循环。
var items = ['one','two','three'], i = items.length;
while(i--){
console.log(items[i]);
}
logs: 'three','two','one'
日志:“三”,“两个”,“一个”
Or the classical for
loop
或者是经典的for循环。
var items = ['one','two','three']
for(var i=0, l = items.length; i < l; i++){
console.log(items[i]);
}
logs: 'one','two','three'
日志:“1”,“2”,“3”
Reference: http://www.sitepoint.com/google-closure-how-not-to-write-javascript/
参考:http://www.sitepoint.com/google-closure-how-not-to-write-javascript/
#8
45
Intro
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.
自从我上大学以来,我已经编程了Java, JavaScript, Pascal, ABAP, PHP, Progress 4GL, C/ c++,可能还有其他一些我现在想不起来的语言。
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, and WHILE
-loops.
虽然它们都有各自的语言特性,但每种语言都有许多相同的基本概念。这些概念包括过程/函数、if语句、for循环和while循环。
A traditional for
-loop
A traditional for
loop has three components:
传统的for循环有三个组件:
- The initialization: executed before the look block is executed the first time
- 初始化:在第一次执行外观块之前执行。
- The condition: checks a condition every time before the loop block is executed, and quits the loop if false
- 条件:每次执行循环块之前检查一个条件,并在错误的情况下退出循环。
- The afterthought: performed every time after the loop block is executed
- 事后想法:在执行循环块后执行。
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 minimal for
loop possible:
这三个分量由a分开;的象征。这三个组件的内容都是可选的,这意味着以下是尽可能少的循环:
for (;;) {
// Do stuff
}
Of course, you will need to include an if(condition === true) { break; }
or an if(condition === true) { return; }
somewhere inside that for
-loop to get it to stop running.
当然,您需要包含if(条件== true) {break;}或if(条件== true){返回;在for循环内的某个地方让它停止运行。
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:
通常,初始化用于声明一个索引,该条件用于将该索引与最小值或最大值进行比较,然后使用afterthought来增加索引:
for (var i = 0, length = 10; i < length; i++) {
console.log(i);
}
Using a traditional for
loop to loop through an array
The traditional way to loop through an array, is this:
传统的循环数组的方法是:
for (var i = 0, length = myArray.length; i < length; i++) {
console.log(myArray[i]);
}
Or, if you prefer to loop backwards, you do this:
或者,如果你倾向于反向循环,你可以这样做:
for (var i = myArray.length - 1; i > -1; i--) {
console.log(myArray[i]);
}
There are, however, many variations possible, like for example this one:
然而,有许多变化可能,例如这一个:
for (var key = 0, value = myArray[key], length = myArray.length; key < length; value = myArray[++key]) {
console.log(value);
}
... or this one ...
…或者这一个…
var i = 0, length = myArray.length;
for (; i < length;) {
console.log(myArray[i]);
i++;
}
... or this one:
…或者这一个:
var key = 0, value;
for (; value = myArray[key++];){
console.log(value);
}
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
loop
One alternative to a for
loop is a while
loop. To loop through an array, you could do this:
for循环的一个替代方案是while循环。要对数组进行循环,可以这样做:
var key = 0;
while(value = myArray[key++]){
console.log(value);
}
Like traditional for
loops, while
loops are supported by even the oldest of browsers.
和传统的for循环一样,即使是最古老的浏览器也支持循环。
Also, note that every while loop can be rewritten as a for
loop. For example, the while
loop hereabove behaves the exact same way as this for
-loop:
还要注意,每个while循环都可以被重写为for循环。例如,上面的while循环的行为与For循环完全相同:
for(var key = 0; value = myArray[key++];){
console.log(value);
}
For...in
and for...of
In JavaScript, you can also do this:
在JavaScript中,也可以这样做:
for (i in myArray) {
console.log(myArray[i]);
}
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" with array iteration a bad idea? for more details.
但是,这应该与care一起使用,因为它在所有情况下都不像传统的for循环,并且有潜在的副作用需要考虑。看看为什么用“for…”在“数组迭代中,一个坏主意?”为更多的细节。
As an alternative to for...in
, there's now also for for...of
. The following example shows the difference between a for...of
loop and a for...in
loop:
作为替代……现在,还有……下面的示例显示了for…循环和a的for…在循环:
var myArray = [3, 5, 7];
myArray.foo = "hello";
for (var i in myArray) {
console.log(i); // logs 0, 1, 2, "foo"
}
for (var i of myArray) {
console.log(i); // logs 3, 5, 7
}
Additionally, you need to consider that no version of Internet Explorer supports for...of
(Edge 12+ does) and that for...in
requires at least Internet Explorer 10.
此外,您需要考虑的是,没有任何版本的Internet Explorer支持……(12+ do)和…至少需要Internet Explorer 10。
Array.prototype.forEach()
An alternative to for
-loops is Array.prototype.forEach()
, which uses the following syntax:
for循环的替代方法是Array.prototype.forEach(),它使用以下语法:
myArray.forEach(function(value, key, myArray) {
console.log(value);
});
Array.prototype.forEach()
is supported by all modern browsers, as well as Internet Explorer 9 and later.
foreach()是由所有现代浏览器以及Internet Explorer 9和后来的浏览器所支持的。
Libraries
Finally, many utility libraries also have their own foreach
variation. AFAIK, the three most popular ones are these:
最后,许多实用程序库也有自己的foreach变体。AFAIK,最受欢迎的三个是:
jQuery.each()
, in jQuery:
在jQuery jQuery.each():
$.each(myArray, function(key, value) {
console.log(value);
});
_.each()
, in Underscore.js:
在Underscore.js _.each():
_.each(myArray, function(value, key, myArray) {
console.log(value);
});
_.forEach()
, in Lodash.js:
在Lodash.js _.forEach():
_.forEach(myArray, function(value, key) {
console.log(value);
});
#9
35
If you want a terse way to write a fast loop and you can iterate in reverse:
如果你想要一个简洁的方法来编写一个快速循环,你可以迭代反向:
for (var i=myArray.length;i--;){
var item=myArray[i];
}
This has the benefit of caching the length (similar to for (var i=0, len=myArray.length; i<len; ++i)
and unlike for (var i=0; i<myArray.length; ++i)
) while being fewer characters to type.
这有缓存长度的好处(类似于var i=0, len=myArray.length;我 <兰;+i)不像(var i="0;我<" myarray.length;(++i),同时字符更少的类型。< p>
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.
甚至有一些时候,您应该以相反的方式迭代,例如,在您计划在迭代期间从DOM中删除项目时迭代一个活的NodeList。
#10
26
There is a way to do it where you have very little implicit scope in your loop and do away with extra variables.
有一种方法可以在你的循环中有非常小的隐式作用域,并去除额外的变量。
var i = 0,
item;
// note this is weak to sparse arrays or falsey values
for ( ; item = myStringArray[i++] ; ){
item; // This is the string at the index.
}
Or if you really want to get the id and have a really classical for
loop:
或者如果你真的想要得到id并且有一个非常经典的for循环:
var i = 0,
len = myStringArray.length; // cache the length
for ( ; i < len ; i++ ){
myStringArray[i]; // Don't use this if you plan on changing the length of the array
}
Modern browsers all support iterator methods forEach
, map
, reduce
, filter
and a host of other methods on the Array prototype.
现代的浏览器都支持迭代器方法,在数组原型中,对每个方法,map, reduce, filter和许多其他方法。
#11
26
There are various way to loop through array in JavaScript.
在JavaScript中有各种各样的方法来循环数组。
Generic loop:
通用的循环:
var i;
for (i = 0; i < substr.length; ++i) {
// Do something with `substr[i]`
}
ES5's forEach:
ES5的forEach:
substr.forEach(function(item) {
// Do something with `item`
});
jQuery.each:
jQuery.each:
jQuery.each(substr, function(index, item) {
// Do something with `item` (or `this` is also `item` if you like)
});
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.
您可以查看此详细信息,或者您也可以检查MDN在JavaScript中的数组循环,并使用jQuery检查jQuery。
#12
25
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.
我将彻底推荐使用下划线。js库。它为您提供了用于迭代数组/集合的各种函数。
For instance:
例如:
_.each([1, 2, 3], function(num){ alert(num); });
=> alerts each number in turn...
#13
22
Array loop:
数组循环:
for(var i = 0; i < things.length; i++){
var thing = things[i];
console.log(thing);
}
Object loop:
对象循环:
for(var prop in obj){
var propValue = obj[prop];
console.log(propValue);
}
#14
19
If you're using the jQuery library, consider using http://api.jquery.com/jQuery.each/
如果您正在使用jQuery库,请考虑使用http://api.jquery.com/jQuery.each/。
From the documentation:
从文档:
jQuery.each( collection, callback(indexInArray, valueOfElement) )
jQuery。每个(集合,回调(indexInArray, valueOfElement))
Returns: Object
返回:对象
Description: A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. Arrays and array-like objects with a length property (such as a function's arguments object) are iterated by numeric index, from 0 to length-1. Other objects are iterated via their named properties.
描述:一个通用的迭代器函数,它可以用来对对象和数组进行无缝的迭代。数组和具有长度属性的数组类对象(例如函数的参数对象)都是由数字索引迭代的,从0到长度1。其他对象通过它们的命名属性进行迭代。
The
$.each()
function is not the same as$(selector).each()
, which is used to iterate, exclusively, over a jQuery object. The$.each()
function can be used to iterate over any collection, whether it is a map (JavaScript object) or an array. In the case of an array, the callback is passed an array index and a corresponding array value each time. (The value can also be accessed through thethis
keyword, but Javascript will always wrap thethis
value as anObject
even if it is a simple string or number value.) The method returns its first argument, the object that was iterated.$.each()函数不等同于$(选择器).each(),它被用于迭代,只对jQuery对象进行迭代。$.each()函数可用于遍历任何集合,无论是映射(JavaScript对象)还是数组。在数组的情况下,每次都传递一个数组索引和相应的数组值。(也可以通过这个关键字来访问该值,但是Javascript始终将该值包装为对象,即使它是一个简单的字符串或数字值。)该方法返回第一个参数,迭代的对象。
#15
19
Yes, you can do the same in JavaScript using loop, but not limited to that, many ways to do loop over arrays in JavaScrip, imagine you have this array below and you'd like to do a loop over it:
是的,你可以在JavaScript中使用循环来做同样的事情,但不限于此,很多方法在JavaScrip中对数组进行循环,假设你有下面这个数组,你想对它做一个循环:
var arr = [1, 2, 3, 4, 5];
These are the solutions:
这些解决方案:
1) For loop
1)For循环
For loop is a common way looping through arrays in JavaScript, but no considered as the fastest solutions for large arrays:
For循环是在JavaScript中循环遍历数组的常用方法,但是对于大型数组来说,它并不是最快的解决方案:
for (var i=0, l=arr.length; i<l; i++) {
console.log(arr[i]);
}
2) While loop
2)While循环
While loop considered as the fastest way to loop through long arrays, but usually less used in the JavaScript:
While循环被认为是通过长数组进行循环的最快方法,但通常在JavaScript中使用较少:
let i=0;
while (arr.length>i) {
console.log(arr[i]);
i++;
}
3) Do while
Do while doing the same thing as while with some syntax difference as below:
3)在做同一件事的同时,做一些语法上的区别:
let i=0;
do {
console.log(arr[i]);
i++;
}
while (arr.length>i);
These are the main ways to do javascript loops, but there are few more ways to do that.
这些是执行javascript循环的主要方法,但是有更多的方法可以做到这一点。
Also we use for in
loop for looping over objects in javascript.
我们还使用for循环来遍历javascript中的对象。
Also look at map()
, filter()
, reduce()
etc functions on Array in JavaScript. They may do things much faster and better than using while
and for
.
还可以在JavaScript中查看map()、filter()、reduce()等函数。他们可能做的事情比用的时间和时间要快得多。
This is good article if you like to learn more about the async functions over arrays in JavaScript.
这是一篇很好的文章,如果您想了解更多关于JavaScript中数组的async函数。
Functional programming has been making quite a splash in the development world these days. And for good reason: Functional techniques can help you write more declarative code that is easier to understand at a glance, refactor, and test.
函数式编程在当今的发展中已经引起了不小的轰动。而且有充分的理由:功能技术可以帮助您编写更易于理解的声明性代码,这些代码更容易理解、重构和测试。
One of the cornerstones of functional programming is its special use of lists and list operations. And those things are exactly what the sound like they are: arrays of things, and the stuff you do to them. But the functional mindset treats them a bit differently than you might expect.
函数式编程的基石之一是它对列表和列表操作的特殊使用。这些东西就像它们的声音一样:事物的排列,以及你对它们所做的事情。但是,功能性的心态对待他们的方式与你想象的有些不同。
This article will take a close look at what I like to call the "big three" list operations: map, filter, and reduce. Wrapping your head around these three functions is an important step towards being able to write clean functional code, and opens the doors to the vastly powerful techniques of functional and reactive programming.
本文将仔细研究我所称的“三大”列表操作:map、filter和reduce。将您的头部绕在这三个函数上是实现编写干净的函数代码的重要步骤,并为功能和反应性编程的强大功能打开了大门。
It also means you'll never have to write a for loop again.
这也意味着你再也不用写一个for循环了。
Read more>> here:
阅读更多> >:
#16
16
I did not yet see this variation, which I personally like the best:
我还没有看到这种变化,我个人最喜欢的是:
Given an array:
给定一个数组:
var someArray = ["some", "example", "array"];
You can loop over it without ever accessing the length property:
你可以在不访问长度属性的情况下对其进行循环:
for (var i=0, item; item=someArray[i]; i++) {
// item is "some", then "example", then "array"
// i is the index of item in the array
alert("someArray[" + i + "]: " + item);
}
See this JsFiddle demonstrating that: http://jsfiddle.net/prvzk/
看到这个JsFiddle演示了: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.
这只适用于不稀疏的数组。这意味着数组中的每个索引实际上都有一个值。然而,我发现在实践中,我很少使用Javascript中的稀疏数组…在这种情况下,使用对象作为map/hashtable通常要容易得多。如果你有一个稀疏数组,并且想要循环到0。长度-1,需要for (var i=0;我< someArray.length;+i)构造,但在循环中仍然需要一个if,以检查当前索引中的元素是否已被定义。
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 :)
另外,正如CMS在评论中提到的,您只能在不包含任何伪造值的数组中使用它。这个示例中的字符串数组是有效的,但是如果您有空字符串,或者是0或NaN的数字,那么循环将会提前终止。在实践中,这对我来说几乎是一个问题,但这是需要记住的,在你使用它之前,这是一个循环思考的问题……这可能会使一些人失去资格:)
What I like about this loop is:
我喜欢这个循环的地方是:
- It's short to write
- 它是短的写
- No need to access (let alone cache) the length property
- 不需要访问(更不用说缓存)长度属性。
- The item to access is automatically defined within the loop body under the name you pick.
- 要访问的项在循环体中自动定义为您选择的名称。
- Combines very naturally with array.push and array.splice to use arrays like lists/stacks
- 与数组很自然地结合。推动和数组。splice使用数组(如列表/堆栈)。
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:
对我来说,这个构造最接近我喜欢的Java 5语法:
for (String item : someArray) {
}
... with the added benefit of also knowing about the current index inside the loop
…还有一个附加的好处,就是了解循环中的当前索引。
#17
14
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.
在JavaScript中有几种方法。前两个示例是JavaScript示例。第三种方法是使用JavaScript库,即jQuery使用.each()函数。
var myStringArray = ["hello", "World"];
for(var i in myStringArray) {
alert(myStringArray[i]);
}
var myStringArray = ["hello", "World"];
for (var i=0; i < myStringArray.length; i++) {
alert(myStringArray[i]);
}
var myStringArray = ["hello", "World"];
$.each(myStringArray, function(index, value){
alert(value);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
#18
14
The most elegant and fast way
var arr = [1, 2, 3, 1023, 1024];
for (var value; value = arr.pop();) {
value + 1
}
http://jsperf.com/native-loop-performance/8
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.
通过对100,000个项目的数组进行循环比较,并每次使用新的值进行最小操作。
- http://jsben.ch/#/BQhED
- http://jsben.ch/ / BQhED
Preparation:
准备:
<script src="//code.jquery.com/jquery-2.1.0.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.6.0/underscore-min.js"></script>
<script>
Benchmark.prototype.setup = function() {
// Fake function with minimal action on the value
var tmp = 0;
var process = function(value) {
tmp = value; // Hold a reference to the variable (prevent engine optimisation?)
};
// Declare the test Array
var arr = [];
for (var i = 0; i < 100000; i++)
arr[i] = i;
};
</script>
Tests:
测试:
<a href="http://jsperf.com/native-loop-performance/16"
title="http://jsperf.com/native-loop-performance/16"
><img src="http://i.imgur.com/YTrO68E.png" title="Hosted by imgur.com" /></a>
#19
13
There's a method to iterate over only own object properties, not including prototype's ones:
有一种方法来遍历自己的对象属性,而不包括原型的:
for (var i in array) if (array.hasOwnProperty(i)) {
// do something with array[i]
}
but it still will iterate over custom-defined properties.
但是它仍然会迭代自定义的属性。
In javascript any custom property could be assigned to any object including array.
在javascript中,任何自定义属性都可以分配给任何对象,包括数组。
If one wants to iterate over sparsed array, for (var i = 0; i < array.length; i++) if (i in array)
or array.forEach
with es5shim
should be used.
如果你想迭代sparsed数组,for (var i = 0;我< array.length;i++) if (i in array)或数组。应该使用es5shim。
#20
10
The optimized approach is to cache the length of array and using single var pattern initializing all variables with single var keyword.
优化的方法是缓存数组的长度,并使用单个var模式初始化所有变量,并使用单个var关键字。
var i, max, myStringArray = ["Hello","World"];
for (i = 0, max = myStringArray.length; i < max; i++) {
alert(myStringArray[i]);
//Do something
}
If order of iteration does not matter than you should try reversed loop, it is fastest as it reduce overhead condition testing and decrement is in one statement:
如果迭代的顺序不重要,那么您应该尝试反向循环,它是最快的,因为它减少了负载条件测试和减量在一个语句中:
var i,myStringArray = ["item1","item2"];
for (i = myStringArray.length; i--) {
alert(myStringArray[i]);
}
or better and cleaner to use while loop:
或更好更清洁的使用while循环:
var myStringArray = ["item1","item2"],i = myStringArray.length;
while(i--) {
// do something with fruits[i]
}
#21
10
In JavaScript, there are so many solutions to loop an array.
在JavaScript中,有很多方法来循环一个数组。
The code below are popular ones
下面的代码很受欢迎。
/** Declare inputs */
const items = ['Hello', 'World']
/** Solution 1. Simple for */
console.log('solution 1. simple for')
for (let i = 0; i < items.length; i++) {
console.log(items[i])
}
console.log()
console.log()
/** Solution 2. Simple while */
console.log('solution 2. simple while')
let i = 0
while (i < items.length) {
console.log(items[i++])
}
console.log()
console.log()
/** Solution 3. forEach*/
console.log('solution 3. forEach')
items.forEach(item => {
console.log(item)
})
console.log()
console.log()
/** Solution 4. for-of*/
console.log('solution 4. for-of')
for (const item of items) {
console.log(item)
}
console.log()
console.log()
#22
9
Short answer: yes. You can do with this:
简短的回答:是的。你可以这样做:
var myArray = ["element1", "element2", "element3", "element4"];
for (i = 0; i < myArray.length; i++) {
console.log(myArray[i]);
}
In a browser console, you can see something like "element1", "element2", etc., printed.
在浏览器控制台中,您可以看到一些类似“element1”、“element2”之类的东西。
#23
9
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 i available, it is certainly the safest way to iterate over an array in JavaScript.
我认为最好的方法是使用数组。为每一个函数。如果您不能使用,我建议从MDN中获取polyfill以使我可用,这当然是在JavaScript中迭代数组的最安全的方法。
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
So as others has suggested, this is almost always what you want:
正如其他人所建议的,这几乎总是你想要的:
var numbers = [1,11,22,33,44,55,66,77,88,99,111];
var sum = 0;
numbers.forEach(function(n){
sum += n;
});
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 it's scope with the rest of your program, the { } does not create a new scope.
在大多数情况下,使用常规的c样式循环工作,记住循环中的所有内容与程序的其他部分共享它的范围是很重要的,{}并没有创建一个新的范围。
Hence:
因此:
var sum = 0;
var numbers = [1,11,22,33,44,55,66,77,88,99,111];
for(var i = 0; i<numbers.length; ++i){
sum += numbers[i];
}
alert(i);
will output "11" - which may or may not be what you want.
输出“11”——它可能是您想要的,也可能不是您想要的。
Working jsFiddle example: https://jsfiddle.net/workingClassHacker/pxpv2dh5/7/
工作jsFiddle示例:https://jsfiddle.net/workingClassHacker/pxpv2dh5/7/
#24
8
For example, I used in a Firefox console:
例如,我在一个Firefox控制台中使用:
[].forEach.call(document.getElementsByTagName('pre'), function(e){
console.log(e);
})
#25
8
var x = [4, 5, 6];
for (i = 0, j = x[i]; i < x.length; j = x[++i]) {
console.log(i,j);
}
A lot cleaner...
很多清洁工……
#26
7
Some use cases of looping through an array in the functional programming way in JavaScript:
在JavaScript的函数式编程方式中,一些用例循环遍历一个数组:
1. Just loop through an array
const myArray = [{x:100}, {x:200}, {x:300}];
myArray.forEach((element, index, array) => {
console.log(element.x); // 100, 200, 300
console.log(index); // 0, 1, 2
console.log(array); // same myArray object 3 times
});
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.
注意:Array.prototype.forEach()不是严格意义上的函数方式,因为作为输入参数的函数不应该返回一个值,因此不能将其视为纯函数。
2. Check if any of the elements in an array pass a test
const people = [
{name: 'John', age: 23},
{name: 'Andrew', age: 3},
{name: 'Peter', age: 8},
{name: 'Hanna', age: 14},
{name: 'Adam', age: 37}];
const anyAdult = people.some(person => person.age >= 18);
console.log(anyAdult); // true
3. Transform to a new array
const myArray = [{x:100}, {x:200}, {x:300}];
const newArray= myArray.map(element => element.x);
console.log(newArray); // [100, 200, 300]
Note: The map() method creates a new array with the results of calling a provided function on every element in the calling array.
注意:map()方法创建一个新的数组,其结果是调用调用数组中的每个元素的函数。
4. Sum up a particular property, and calculate its average
const myArray = [{x:100}, {x:200}, {x:300}];
const sum = myArray.map(element => element.x).reduce((a, b) => a + b, 0);
console.log(sum); // 600 = 0 + 100 + 200 + 300
const average = sum / myArray.length;
console.log(average); // 200
5. Create a new array based on the original but without modifying it
const myArray = [{x:100}, {x:200}, {x:300}];
const newArray= myArray.map(element => {
return {
...element,
x: element.x * 2
};
});
console.log(myArray); // [100, 200, 300]
console.log(newArray); // [200, 400, 600]
6. Count the number of each category
const people = [
{name: 'John', group: 'A'},
{name: 'Andrew', group: 'C'},
{name: 'Peter', group: 'A'},
{name: 'James', group: 'B'},
{name: 'Hanna', group: 'A'},
{name: 'Adam', group: 'B'}];
const groupInfo = people.reduce((groups, person) => {
const {A = 0, B = 0, C = 0} = groups;
if (person.group === 'A') {
return {...groups, A: A + 1};
} else if (person.group === 'B') {
return {...groups, B: B + 1};
} else {
return {...groups, C: C + 1};
}
}, {});
console.log(groupInfo); // {A: 3, C: 1, B: 2}
7. Retrieve a subset of an array based on particular criteria
const myArray = [{x:100}, {x:200}, {x:300}];
const newArray = myArray.filter(element => element.x > 250);
console.log(newArray); // [{x:300}]
Note: The filter() method creates a new array with all elements that pass the test implemented by the provided function.
注意:filter()方法创建了一个新的数组,其中包含了通过提供的函数实现的测试的所有元素。
8. Sort an array
const people = [
{ name: "John", age: 21 },
{ name: "Peter", age: 31 },
{ name: "Andrew", age: 29 },
{ name: "Thomas", age: 25 }
];
let sortByAge = people.sort(function (p1, p2) {
return p1.age - p2.age;
});
console.log(sortByAge);
References
- Array.prototype.some()
- Array.prototype.some()
- Array.prototype.forEach()
- Array.prototype.forEach()
- Array.prototype.map()
- Array.prototype.map()
- Array.prototype.filter()
- Array.prototype.filter()
- Array.prototype.sort()
- Array.prototype.sort()
- Spread syntax
- 传播的语法
#27
6
Sure it's inefficient and many despise it, but it's one of the closest to the mentioned:
当然,它是低效的,许多人轻视它,但它是最接近提到的:
var myStringArray = ["Hello","World"];
myStringArray.forEach(function(f){
// Do something
})
#28
6
If you want to use jQuery, it has a nice example in its documentation:
如果您想使用jQuery,它在文档中有一个很好的例子:
$.each([ 52, 97 ], function( index, value ) {
alert( index + ": " + value );
});
#29
5
Well, how about this:
那么,这个怎么样:
for (var key in myStringArray) {
console.log(myStringArray[key]);
}
#30
5
var myStringArray = ["hello", "World"];
myStringArray.forEach(function(val, index){
console.log(val, index);
})
#1
2943
Use a sequential for
loop:
使用顺序for循环:
var myStringArray = ["Hello","World"];
var arrayLength = myStringArray.length;
for (var i = 0; i < arrayLength; i++) {
alert(myStringArray[i]);
//Do something
}
@zipcodeman suggests the use of the for...in
statement, but for iterating arrays for-in
should be avoided, that statement is meant to enumerate object properties.
@zipcodeman建议使用for…在语句中,但要避免迭代数组,该语句的目的是枚举对象属性。
It shouldn't be used for array-like objects because:
它不应该用于arraylike对象,因为:
- The order of iteration is not guaranteed, the array indexes may not be visited in numeric order.
- 迭代的顺序没有保证,数组索引可能不会以数字顺序访问。
- Inherited properties are also enumerated.
- 继承的属性也被枚举。
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 be also enumerated.
第二点是它可以给你很多问题,例如,如果你扩展数组。原型对象中包含一个方法,该属性也将被枚举。
For example:
例如:
Array.prototype.foo = "foo!";
var array = ['a', 'b', 'c'];
for (var i in array) {
alert(array[i]);
}
The above code will alert, "a", "b", "c" and "foo!".
上面的代码会提示,“a”,“b”,“c”和“foo!”
That be particularly a problem if you use some library that relies heavily on native prototypes augmention (such as MooTools for example).
如果您使用大量依赖本机原型的库(例如MooTools),那么这将是一个特别的问题。
The for-in
statement as I said before is there to enumerate object properties, for example:
我之前说过的forin语句是用来枚举对象属性的,例如:
var obj = {
"a": 1,
"b": 2,
"c": 3
};
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
// or if (Object.prototype.hasOwnProperty.call(obj,prop)) for safety...
alert("prop: " + prop + " value: " + obj[prop])
}
}
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.
在上面的例子中,hasOwnProperty方法允许您只枚举自己的属性,也就是它,只是对象物理上拥有的属性,没有继承属性。
I would recommend you to read the following article:
我建议您阅读以下文章:
- Enumeration VS Iteration
- 枚举和迭代
#2
795
Yes, but only if your implementation includes the for
...of
feature introduced in ECMAScript 2015 (the "Harmony" release).
是的,但前提是你的实现包括……2015年ECMAScript(“和谐”版本)中引入的功能。
It works like this:
是这样的:
// REQUIRES ECMASCRIPT 2015+
var s, myStringArray = ["Hello", "World"];
for (s of myStringArray) {
// ... do something with s ...
}
Or better yet, since ECMAScript 2015 also provides block-scoped variables via let
and const
:
或者更好,因为ECMAScript 2015还通过let和const提供了块范围的变量:
// REQUIRES ECMASCRIPT 2015+
const myStringArray = ["Hello", "World"];
for (let s of myStringArray) {
// ... do something with s ...
}
// s is no longer defined here
Many JavaScript developers are still working in an environment that's not there yet, however - especially if writing code to run in web browsers, where the site developers often can't be sure what browser/version their clients will be using.
许多JavaScript开发人员仍然在一个尚未开发的环境中工作——特别是如果在web浏览器中编写代码,站点开发人员常常无法确定他们的客户将使用什么浏览器/版本。
If you can assume the JavaScript interpreter 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 forEach
iterator method instead of a loop. In that case, you pass a function to be called on each item in the array:
如果您可以假设JavaScript解释器符合ECMAScript规范的前一个版本(例如,在9之前就排除了Internet Explorer的版本),那么您可以使用forEach迭代器方法而不是一个循环。在这种情况下,您传递一个函数来调用数组中的每个项:
var myStringArray = [ "Hello", "World" ];
myStringArray.forEach( function(s) {
// ... do something with s ...
} );
But if even that is too much to assume, and you want something that works in all versions of JavaScript, then you have to use an explicit counting loop. The safest version, which handles sparse arrays properly, is something like this:
但是,如果这是太多的假设,并且您希望在所有的JavaScript版本中都有工作,那么您必须使用一个显式计数循环。最安全的处理稀疏数组的版本是这样的:
var i, s, myStringArray = [ "Hello", "World" ], len = myStringArray.length;
for (i=0; i<len; ++i) {
if (i in myStringArray) {
s = myStringArray[i];
// ... do something with s ...
}
}
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; using Rhino on my machine, the speedup is 43%.
将长度值分配给局部变量(而不是包括完整的myStringArray)。在循环条件下的长度表达式)可以在性能上产生显著的差异,因为它每次都跳过属性查找;在我的机器上使用Rhino,加速率为43%。
You will often see the length caching done in the loop initialization clause, like this:
您将经常看到在循环初始化子句中完成的长度缓存:
var i, len, myStringArray = [ "Hello", "World" ];
for (len = myStringArray.length, i=0; i<len; ++i) {
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-updated length
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 does it iterate over those in numeric order. Therefore, the for
...in
syntax should not be used for looping through Arrays.
为…在语法中,别人提到的是对对象的属性进行循环;由于JavaScript中的数组只是一个具有数字属性名的对象(以及一个自动更新的长度属性),所以理论上可以对数组进行循环。但问题是,它并不局限于数字属性值(请记住,即使方法实际上只是值为闭包的属性),也不会对那些数字顺序进行迭代。因此,……在语法中不应该用于遍历数组。
#3
383
You can use map
, which is a functional programming technique that's also available in other languages like Python and Haskell.
您可以使用map,这是一种函数式编程技术,也可以使用其他语言,如Python和Haskell。
[1,2,3,4].map( function(item) {
alert(item);
})
The general syntax is:
一般的语法是:
array.map(func)
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.
一般来说,func会取一个参数,它是数组的一个项。但是在JavaScript的情况下,它可以使用第二个参数,它是项的索引,第三个参数是数组本身。
The return value of array.map
is another array, so you can use it like this:
数组的返回值。map是另一个数组,所以可以这样使用:
var x = [1,2,3,4].map( function(item) {return item * 10;});
And now x is [10,20,30,40]
.
现在x是(10,20,30,40)
You don't have to write the function inline. It could be a separate function.
你不需要内联写函数。它可以是一个单独的函数。
var item_processor = function(item) {
// Do something complicated to an item
}
new_list = my_list.map(item_processor);
which would be sort-of equivalent to:
这相当于:
for (item in my_list) {item_processor(item);}
Except you don't get the new_list
.
除非你没有得到new_list。
#4
97
In JavaScript it's not advisable to loop through an Array with a for-in loop, but it's better using a for loop such as:
在JavaScript中,用forin循环遍历数组是不明智的,但是最好使用for循环,例如:
for(var i=0, len=myArray.length; i < len; i++){}
It's optimized as well ("caching" the array length). If you'd like to learn more, read my post on the subject.
它也进行了优化(“缓存”数组长度)。如果你想了解更多,请阅读我关于这个主题的文章。
#5
89
for (var 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 ECMA Script
6
2015 is bringing a new mechanism for doing iteration, the for..of
loop.
大多数其他的答案都是正确的,但是他们没有提到ECMA脚本6 2015正在为迭代开发提供一种新的机制。的循环。
This new syntax is the most elegant way to iterate an array in javascript (as long you don't need the iteration index), but it is not yet widely supported by the browsers.
这种新语法是在javascript中迭代数组的最优雅的方法(因为您不需要迭代索引),但是它还没有得到浏览器的广泛支持。
It currently works with Firefox 13+, Chrome 37+ and it does not natively work with other browsers (see browser compatibility below). Luckily we have JS compilers (such as Babel) that allow us to use next-generation features today.
它目前使用的是Firefox 13+, Chrome 37+,而且它并没有与其他浏览器一起使用(参见下面的浏览器兼容性)。幸运的是,我们有JS编译器(比如Babel),它允许我们今天使用下一代功能。
It also works on Node (I tested it on version 0.12.0).
它也适用于Node(我在0.12.0版上测试过)。
Iterating an array
遍历一个数组
// You could also use "let" instead of "var" for block scope.
for (var letter of ["a", "b", "c"]) {
console.log(letter);
}
Iterating an array of objects
迭代对象数组。
var band = [
{firstName : 'John', lastName: 'Lennon'},
{firstName : 'Paul', lastName: 'McCartney'}
];
for(var member of band){
console.log(member.firstName + ' ' + member.lastName);
}
Iterating a generator:
迭代一个发电机:
(example extracted from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of)
(例如从https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of)中提取
function* fibonacci() { // a generator function
let [prev, curr] = [1, 1];
while (true) {
[prev, curr] = [curr, prev + curr];
yield curr;
}
}
for (let n of fibonacci()) {
console.log(n);
// truncate the sequence at 1000
if (n >= 1000) {
break;
}
}
Compatibility table: http://kangax.github.io/es5-compat-table/es6/#For..of loops
兼容性表:http://kangax.github.io/es5-compat-table/es6/ . .的循环
Spec: http://wiki.ecmascript.org/doku.php?id=harmony:iterators
规范:http://wiki.ecmascript.org/doku.php?id=harmony:迭代器
}
#6
80
Opera, Safari, Firefox and Chrome now all share a set of enhanced Array methods for optimizing many common loops.
Opera、Safari、Firefox和Chrome现在都共享一组增强的数组方法来优化许多常见的循环。
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.
Mozilla实验室发布了他们和WebKit都使用的算法,这样你就可以自己添加它们了。
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.
如果通过测试,一些返回true。
forEach runs a function on each array member and doesn't return anything.
forEach在每个数组成员上运行一个函数,并没有返回任何值。
map is like forEach, but it returns an array of the results of the operation for each element.
map就像forEach,但它返回每个元素的操作结果的数组。
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.
indexOf和lastIndexOf找到匹配其参数的第一个或最后一个元素的适当位置。
(function(){
var p, ap= Array.prototype, p2={
filter: function(fun, scope){
var L= this.length, A= [], i= 0, val;
if(typeof fun== 'function'){
while(i< L){
if(i in this){
val= this[i];
if(fun.call(scope, val, i, this)){
A[A.length]= val;
}
}
++i;
}
}
return A;
},
every: function(fun, scope){
var L= this.length, i= 0;
if(typeof fun== 'function'){
while(i<L){
if(i in this && !fun.call(scope, this[i], i, this))
return false;
++i;
}
return true;
}
return null;
},
forEach: function(fun, scope){
var L= this.length, i= 0;
if(typeof fun== 'function'){
while(i< L){
if(i in this){
fun.call(scope, this[i], i, this);
}
++i;
}
}
return this;
},
indexOf: function(what, i){
i= i || 0;
var L= this.length;
while(i< L){
if(this[i]=== what)
return i;
++i;
}
return -1;
},
lastIndexOf: function(what, i){
var L= this.length;
i= i || L-1;
if(isNaN(i) || i>= L)
i= L-1;
else
if(i< 0) i += L;
while(i> -1){
if(this[i]=== what)
return i;
--i;
}
return -1;
},
map: function(fun, scope){
var L= this.length, A= Array(this.length), i= 0, val;
if(typeof fun== 'function'){
while(i< L){
if(i in this){
A[i]= fun.call(scope, this[i], i, this);
}
++i;
}
return A;
}
},
some: function(fun, scope){
var i= 0, L= this.length;
if(typeof fun== 'function'){
while(i<L){
if(i in this && fun.call(scope, this[i], i, this))
return true;
++i;
}
return false;
}
}
}
for(p in p2){
if(!ap[p])
ap[p]= p2[p];
}
return true;
})();
#7
62
Use the while loop...
使用while循环……
var i=0, item, items = ['one','two','three'];
while(item = items[i++]){
console.log(item);
}
logs: 'one','two','three'
日志:“1”,“2”,“3”
And for the reverse order, an even more efficient loop
对于相反的顺序,一个更有效的循环。
var items = ['one','two','three'], i = items.length;
while(i--){
console.log(items[i]);
}
logs: 'three','two','one'
日志:“三”,“两个”,“一个”
Or the classical for
loop
或者是经典的for循环。
var items = ['one','two','three']
for(var i=0, l = items.length; i < l; i++){
console.log(items[i]);
}
logs: 'one','two','three'
日志:“1”,“2”,“3”
Reference: http://www.sitepoint.com/google-closure-how-not-to-write-javascript/
参考:http://www.sitepoint.com/google-closure-how-not-to-write-javascript/
#8
45
Intro
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.
自从我上大学以来,我已经编程了Java, JavaScript, Pascal, ABAP, PHP, Progress 4GL, C/ c++,可能还有其他一些我现在想不起来的语言。
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, and WHILE
-loops.
虽然它们都有各自的语言特性,但每种语言都有许多相同的基本概念。这些概念包括过程/函数、if语句、for循环和while循环。
A traditional for
-loop
A traditional for
loop has three components:
传统的for循环有三个组件:
- The initialization: executed before the look block is executed the first time
- 初始化:在第一次执行外观块之前执行。
- The condition: checks a condition every time before the loop block is executed, and quits the loop if false
- 条件:每次执行循环块之前检查一个条件,并在错误的情况下退出循环。
- The afterthought: performed every time after the loop block is executed
- 事后想法:在执行循环块后执行。
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 minimal for
loop possible:
这三个分量由a分开;的象征。这三个组件的内容都是可选的,这意味着以下是尽可能少的循环:
for (;;) {
// Do stuff
}
Of course, you will need to include an if(condition === true) { break; }
or an if(condition === true) { return; }
somewhere inside that for
-loop to get it to stop running.
当然,您需要包含if(条件== true) {break;}或if(条件== true){返回;在for循环内的某个地方让它停止运行。
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:
通常,初始化用于声明一个索引,该条件用于将该索引与最小值或最大值进行比较,然后使用afterthought来增加索引:
for (var i = 0, length = 10; i < length; i++) {
console.log(i);
}
Using a traditional for
loop to loop through an array
The traditional way to loop through an array, is this:
传统的循环数组的方法是:
for (var i = 0, length = myArray.length; i < length; i++) {
console.log(myArray[i]);
}
Or, if you prefer to loop backwards, you do this:
或者,如果你倾向于反向循环,你可以这样做:
for (var i = myArray.length - 1; i > -1; i--) {
console.log(myArray[i]);
}
There are, however, many variations possible, like for example this one:
然而,有许多变化可能,例如这一个:
for (var key = 0, value = myArray[key], length = myArray.length; key < length; value = myArray[++key]) {
console.log(value);
}
... or this one ...
…或者这一个…
var i = 0, length = myArray.length;
for (; i < length;) {
console.log(myArray[i]);
i++;
}
... or this one:
…或者这一个:
var key = 0, value;
for (; value = myArray[key++];){
console.log(value);
}
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
loop
One alternative to a for
loop is a while
loop. To loop through an array, you could do this:
for循环的一个替代方案是while循环。要对数组进行循环,可以这样做:
var key = 0;
while(value = myArray[key++]){
console.log(value);
}
Like traditional for
loops, while
loops are supported by even the oldest of browsers.
和传统的for循环一样,即使是最古老的浏览器也支持循环。
Also, note that every while loop can be rewritten as a for
loop. For example, the while
loop hereabove behaves the exact same way as this for
-loop:
还要注意,每个while循环都可以被重写为for循环。例如,上面的while循环的行为与For循环完全相同:
for(var key = 0; value = myArray[key++];){
console.log(value);
}
For...in
and for...of
In JavaScript, you can also do this:
在JavaScript中,也可以这样做:
for (i in myArray) {
console.log(myArray[i]);
}
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" with array iteration a bad idea? for more details.
但是,这应该与care一起使用,因为它在所有情况下都不像传统的for循环,并且有潜在的副作用需要考虑。看看为什么用“for…”在“数组迭代中,一个坏主意?”为更多的细节。
As an alternative to for...in
, there's now also for for...of
. The following example shows the difference between a for...of
loop and a for...in
loop:
作为替代……现在,还有……下面的示例显示了for…循环和a的for…在循环:
var myArray = [3, 5, 7];
myArray.foo = "hello";
for (var i in myArray) {
console.log(i); // logs 0, 1, 2, "foo"
}
for (var i of myArray) {
console.log(i); // logs 3, 5, 7
}
Additionally, you need to consider that no version of Internet Explorer supports for...of
(Edge 12+ does) and that for...in
requires at least Internet Explorer 10.
此外,您需要考虑的是,没有任何版本的Internet Explorer支持……(12+ do)和…至少需要Internet Explorer 10。
Array.prototype.forEach()
An alternative to for
-loops is Array.prototype.forEach()
, which uses the following syntax:
for循环的替代方法是Array.prototype.forEach(),它使用以下语法:
myArray.forEach(function(value, key, myArray) {
console.log(value);
});
Array.prototype.forEach()
is supported by all modern browsers, as well as Internet Explorer 9 and later.
foreach()是由所有现代浏览器以及Internet Explorer 9和后来的浏览器所支持的。
Libraries
Finally, many utility libraries also have their own foreach
variation. AFAIK, the three most popular ones are these:
最后,许多实用程序库也有自己的foreach变体。AFAIK,最受欢迎的三个是:
jQuery.each()
, in jQuery:
在jQuery jQuery.each():
$.each(myArray, function(key, value) {
console.log(value);
});
_.each()
, in Underscore.js:
在Underscore.js _.each():
_.each(myArray, function(value, key, myArray) {
console.log(value);
});
_.forEach()
, in Lodash.js:
在Lodash.js _.forEach():
_.forEach(myArray, function(value, key) {
console.log(value);
});
#9
35
If you want a terse way to write a fast loop and you can iterate in reverse:
如果你想要一个简洁的方法来编写一个快速循环,你可以迭代反向:
for (var i=myArray.length;i--;){
var item=myArray[i];
}
This has the benefit of caching the length (similar to for (var i=0, len=myArray.length; i<len; ++i)
and unlike for (var i=0; i<myArray.length; ++i)
) while being fewer characters to type.
这有缓存长度的好处(类似于var i=0, len=myArray.length;我 <兰;+i)不像(var i="0;我<" myarray.length;(++i),同时字符更少的类型。< p>
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.
甚至有一些时候,您应该以相反的方式迭代,例如,在您计划在迭代期间从DOM中删除项目时迭代一个活的NodeList。
#10
26
There is a way to do it where you have very little implicit scope in your loop and do away with extra variables.
有一种方法可以在你的循环中有非常小的隐式作用域,并去除额外的变量。
var i = 0,
item;
// note this is weak to sparse arrays or falsey values
for ( ; item = myStringArray[i++] ; ){
item; // This is the string at the index.
}
Or if you really want to get the id and have a really classical for
loop:
或者如果你真的想要得到id并且有一个非常经典的for循环:
var i = 0,
len = myStringArray.length; // cache the length
for ( ; i < len ; i++ ){
myStringArray[i]; // Don't use this if you plan on changing the length of the array
}
Modern browsers all support iterator methods forEach
, map
, reduce
, filter
and a host of other methods on the Array prototype.
现代的浏览器都支持迭代器方法,在数组原型中,对每个方法,map, reduce, filter和许多其他方法。
#11
26
There are various way to loop through array in JavaScript.
在JavaScript中有各种各样的方法来循环数组。
Generic loop:
通用的循环:
var i;
for (i = 0; i < substr.length; ++i) {
// Do something with `substr[i]`
}
ES5's forEach:
ES5的forEach:
substr.forEach(function(item) {
// Do something with `item`
});
jQuery.each:
jQuery.each:
jQuery.each(substr, function(index, item) {
// Do something with `item` (or `this` is also `item` if you like)
});
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.
您可以查看此详细信息,或者您也可以检查MDN在JavaScript中的数组循环,并使用jQuery检查jQuery。
#12
25
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.
我将彻底推荐使用下划线。js库。它为您提供了用于迭代数组/集合的各种函数。
For instance:
例如:
_.each([1, 2, 3], function(num){ alert(num); });
=> alerts each number in turn...
#13
22
Array loop:
数组循环:
for(var i = 0; i < things.length; i++){
var thing = things[i];
console.log(thing);
}
Object loop:
对象循环:
for(var prop in obj){
var propValue = obj[prop];
console.log(propValue);
}
#14
19
If you're using the jQuery library, consider using http://api.jquery.com/jQuery.each/
如果您正在使用jQuery库,请考虑使用http://api.jquery.com/jQuery.each/。
From the documentation:
从文档:
jQuery.each( collection, callback(indexInArray, valueOfElement) )
jQuery。每个(集合,回调(indexInArray, valueOfElement))
Returns: Object
返回:对象
Description: A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. Arrays and array-like objects with a length property (such as a function's arguments object) are iterated by numeric index, from 0 to length-1. Other objects are iterated via their named properties.
描述:一个通用的迭代器函数,它可以用来对对象和数组进行无缝的迭代。数组和具有长度属性的数组类对象(例如函数的参数对象)都是由数字索引迭代的,从0到长度1。其他对象通过它们的命名属性进行迭代。
The
$.each()
function is not the same as$(selector).each()
, which is used to iterate, exclusively, over a jQuery object. The$.each()
function can be used to iterate over any collection, whether it is a map (JavaScript object) or an array. In the case of an array, the callback is passed an array index and a corresponding array value each time. (The value can also be accessed through thethis
keyword, but Javascript will always wrap thethis
value as anObject
even if it is a simple string or number value.) The method returns its first argument, the object that was iterated.$.each()函数不等同于$(选择器).each(),它被用于迭代,只对jQuery对象进行迭代。$.each()函数可用于遍历任何集合,无论是映射(JavaScript对象)还是数组。在数组的情况下,每次都传递一个数组索引和相应的数组值。(也可以通过这个关键字来访问该值,但是Javascript始终将该值包装为对象,即使它是一个简单的字符串或数字值。)该方法返回第一个参数,迭代的对象。
#15
19
Yes, you can do the same in JavaScript using loop, but not limited to that, many ways to do loop over arrays in JavaScrip, imagine you have this array below and you'd like to do a loop over it:
是的,你可以在JavaScript中使用循环来做同样的事情,但不限于此,很多方法在JavaScrip中对数组进行循环,假设你有下面这个数组,你想对它做一个循环:
var arr = [1, 2, 3, 4, 5];
These are the solutions:
这些解决方案:
1) For loop
1)For循环
For loop is a common way looping through arrays in JavaScript, but no considered as the fastest solutions for large arrays:
For循环是在JavaScript中循环遍历数组的常用方法,但是对于大型数组来说,它并不是最快的解决方案:
for (var i=0, l=arr.length; i<l; i++) {
console.log(arr[i]);
}
2) While loop
2)While循环
While loop considered as the fastest way to loop through long arrays, but usually less used in the JavaScript:
While循环被认为是通过长数组进行循环的最快方法,但通常在JavaScript中使用较少:
let i=0;
while (arr.length>i) {
console.log(arr[i]);
i++;
}
3) Do while
Do while doing the same thing as while with some syntax difference as below:
3)在做同一件事的同时,做一些语法上的区别:
let i=0;
do {
console.log(arr[i]);
i++;
}
while (arr.length>i);
These are the main ways to do javascript loops, but there are few more ways to do that.
这些是执行javascript循环的主要方法,但是有更多的方法可以做到这一点。
Also we use for in
loop for looping over objects in javascript.
我们还使用for循环来遍历javascript中的对象。
Also look at map()
, filter()
, reduce()
etc functions on Array in JavaScript. They may do things much faster and better than using while
and for
.
还可以在JavaScript中查看map()、filter()、reduce()等函数。他们可能做的事情比用的时间和时间要快得多。
This is good article if you like to learn more about the async functions over arrays in JavaScript.
这是一篇很好的文章,如果您想了解更多关于JavaScript中数组的async函数。
Functional programming has been making quite a splash in the development world these days. And for good reason: Functional techniques can help you write more declarative code that is easier to understand at a glance, refactor, and test.
函数式编程在当今的发展中已经引起了不小的轰动。而且有充分的理由:功能技术可以帮助您编写更易于理解的声明性代码,这些代码更容易理解、重构和测试。
One of the cornerstones of functional programming is its special use of lists and list operations. And those things are exactly what the sound like they are: arrays of things, and the stuff you do to them. But the functional mindset treats them a bit differently than you might expect.
函数式编程的基石之一是它对列表和列表操作的特殊使用。这些东西就像它们的声音一样:事物的排列,以及你对它们所做的事情。但是,功能性的心态对待他们的方式与你想象的有些不同。
This article will take a close look at what I like to call the "big three" list operations: map, filter, and reduce. Wrapping your head around these three functions is an important step towards being able to write clean functional code, and opens the doors to the vastly powerful techniques of functional and reactive programming.
本文将仔细研究我所称的“三大”列表操作:map、filter和reduce。将您的头部绕在这三个函数上是实现编写干净的函数代码的重要步骤,并为功能和反应性编程的强大功能打开了大门。
It also means you'll never have to write a for loop again.
这也意味着你再也不用写一个for循环了。
Read more>> here:
阅读更多> >:
#16
16
I did not yet see this variation, which I personally like the best:
我还没有看到这种变化,我个人最喜欢的是:
Given an array:
给定一个数组:
var someArray = ["some", "example", "array"];
You can loop over it without ever accessing the length property:
你可以在不访问长度属性的情况下对其进行循环:
for (var i=0, item; item=someArray[i]; i++) {
// item is "some", then "example", then "array"
// i is the index of item in the array
alert("someArray[" + i + "]: " + item);
}
See this JsFiddle demonstrating that: http://jsfiddle.net/prvzk/
看到这个JsFiddle演示了: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.
这只适用于不稀疏的数组。这意味着数组中的每个索引实际上都有一个值。然而,我发现在实践中,我很少使用Javascript中的稀疏数组…在这种情况下,使用对象作为map/hashtable通常要容易得多。如果你有一个稀疏数组,并且想要循环到0。长度-1,需要for (var i=0;我< someArray.length;+i)构造,但在循环中仍然需要一个if,以检查当前索引中的元素是否已被定义。
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 :)
另外,正如CMS在评论中提到的,您只能在不包含任何伪造值的数组中使用它。这个示例中的字符串数组是有效的,但是如果您有空字符串,或者是0或NaN的数字,那么循环将会提前终止。在实践中,这对我来说几乎是一个问题,但这是需要记住的,在你使用它之前,这是一个循环思考的问题……这可能会使一些人失去资格:)
What I like about this loop is:
我喜欢这个循环的地方是:
- It's short to write
- 它是短的写
- No need to access (let alone cache) the length property
- 不需要访问(更不用说缓存)长度属性。
- The item to access is automatically defined within the loop body under the name you pick.
- 要访问的项在循环体中自动定义为您选择的名称。
- Combines very naturally with array.push and array.splice to use arrays like lists/stacks
- 与数组很自然地结合。推动和数组。splice使用数组(如列表/堆栈)。
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:
对我来说,这个构造最接近我喜欢的Java 5语法:
for (String item : someArray) {
}
... with the added benefit of also knowing about the current index inside the loop
…还有一个附加的好处,就是了解循环中的当前索引。
#17
14
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.
在JavaScript中有几种方法。前两个示例是JavaScript示例。第三种方法是使用JavaScript库,即jQuery使用.each()函数。
var myStringArray = ["hello", "World"];
for(var i in myStringArray) {
alert(myStringArray[i]);
}
var myStringArray = ["hello", "World"];
for (var i=0; i < myStringArray.length; i++) {
alert(myStringArray[i]);
}
var myStringArray = ["hello", "World"];
$.each(myStringArray, function(index, value){
alert(value);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
#18
14
The most elegant and fast way
var arr = [1, 2, 3, 1023, 1024];
for (var value; value = arr.pop();) {
value + 1
}
http://jsperf.com/native-loop-performance/8
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.
通过对100,000个项目的数组进行循环比较,并每次使用新的值进行最小操作。
- http://jsben.ch/#/BQhED
- http://jsben.ch/ / BQhED
Preparation:
准备:
<script src="//code.jquery.com/jquery-2.1.0.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.6.0/underscore-min.js"></script>
<script>
Benchmark.prototype.setup = function() {
// Fake function with minimal action on the value
var tmp = 0;
var process = function(value) {
tmp = value; // Hold a reference to the variable (prevent engine optimisation?)
};
// Declare the test Array
var arr = [];
for (var i = 0; i < 100000; i++)
arr[i] = i;
};
</script>
Tests:
测试:
<a href="http://jsperf.com/native-loop-performance/16"
title="http://jsperf.com/native-loop-performance/16"
><img src="http://i.imgur.com/YTrO68E.png" title="Hosted by imgur.com" /></a>
#19
13
There's a method to iterate over only own object properties, not including prototype's ones:
有一种方法来遍历自己的对象属性,而不包括原型的:
for (var i in array) if (array.hasOwnProperty(i)) {
// do something with array[i]
}
but it still will iterate over custom-defined properties.
但是它仍然会迭代自定义的属性。
In javascript any custom property could be assigned to any object including array.
在javascript中,任何自定义属性都可以分配给任何对象,包括数组。
If one wants to iterate over sparsed array, for (var i = 0; i < array.length; i++) if (i in array)
or array.forEach
with es5shim
should be used.
如果你想迭代sparsed数组,for (var i = 0;我< array.length;i++) if (i in array)或数组。应该使用es5shim。
#20
10
The optimized approach is to cache the length of array and using single var pattern initializing all variables with single var keyword.
优化的方法是缓存数组的长度,并使用单个var模式初始化所有变量,并使用单个var关键字。
var i, max, myStringArray = ["Hello","World"];
for (i = 0, max = myStringArray.length; i < max; i++) {
alert(myStringArray[i]);
//Do something
}
If order of iteration does not matter than you should try reversed loop, it is fastest as it reduce overhead condition testing and decrement is in one statement:
如果迭代的顺序不重要,那么您应该尝试反向循环,它是最快的,因为它减少了负载条件测试和减量在一个语句中:
var i,myStringArray = ["item1","item2"];
for (i = myStringArray.length; i--) {
alert(myStringArray[i]);
}
or better and cleaner to use while loop:
或更好更清洁的使用while循环:
var myStringArray = ["item1","item2"],i = myStringArray.length;
while(i--) {
// do something with fruits[i]
}
#21
10
In JavaScript, there are so many solutions to loop an array.
在JavaScript中,有很多方法来循环一个数组。
The code below are popular ones
下面的代码很受欢迎。
/** Declare inputs */
const items = ['Hello', 'World']
/** Solution 1. Simple for */
console.log('solution 1. simple for')
for (let i = 0; i < items.length; i++) {
console.log(items[i])
}
console.log()
console.log()
/** Solution 2. Simple while */
console.log('solution 2. simple while')
let i = 0
while (i < items.length) {
console.log(items[i++])
}
console.log()
console.log()
/** Solution 3. forEach*/
console.log('solution 3. forEach')
items.forEach(item => {
console.log(item)
})
console.log()
console.log()
/** Solution 4. for-of*/
console.log('solution 4. for-of')
for (const item of items) {
console.log(item)
}
console.log()
console.log()
#22
9
Short answer: yes. You can do with this:
简短的回答:是的。你可以这样做:
var myArray = ["element1", "element2", "element3", "element4"];
for (i = 0; i < myArray.length; i++) {
console.log(myArray[i]);
}
In a browser console, you can see something like "element1", "element2", etc., printed.
在浏览器控制台中,您可以看到一些类似“element1”、“element2”之类的东西。
#23
9
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 i available, it is certainly the safest way to iterate over an array in JavaScript.
我认为最好的方法是使用数组。为每一个函数。如果您不能使用,我建议从MDN中获取polyfill以使我可用,这当然是在JavaScript中迭代数组的最安全的方法。
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
So as others has suggested, this is almost always what you want:
正如其他人所建议的,这几乎总是你想要的:
var numbers = [1,11,22,33,44,55,66,77,88,99,111];
var sum = 0;
numbers.forEach(function(n){
sum += n;
});
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 it's scope with the rest of your program, the { } does not create a new scope.
在大多数情况下,使用常规的c样式循环工作,记住循环中的所有内容与程序的其他部分共享它的范围是很重要的,{}并没有创建一个新的范围。
Hence:
因此:
var sum = 0;
var numbers = [1,11,22,33,44,55,66,77,88,99,111];
for(var i = 0; i<numbers.length; ++i){
sum += numbers[i];
}
alert(i);
will output "11" - which may or may not be what you want.
输出“11”——它可能是您想要的,也可能不是您想要的。
Working jsFiddle example: https://jsfiddle.net/workingClassHacker/pxpv2dh5/7/
工作jsFiddle示例:https://jsfiddle.net/workingClassHacker/pxpv2dh5/7/
#24
8
For example, I used in a Firefox console:
例如,我在一个Firefox控制台中使用:
[].forEach.call(document.getElementsByTagName('pre'), function(e){
console.log(e);
})
#25
8
var x = [4, 5, 6];
for (i = 0, j = x[i]; i < x.length; j = x[++i]) {
console.log(i,j);
}
A lot cleaner...
很多清洁工……
#26
7
Some use cases of looping through an array in the functional programming way in JavaScript:
在JavaScript的函数式编程方式中,一些用例循环遍历一个数组:
1. Just loop through an array
const myArray = [{x:100}, {x:200}, {x:300}];
myArray.forEach((element, index, array) => {
console.log(element.x); // 100, 200, 300
console.log(index); // 0, 1, 2
console.log(array); // same myArray object 3 times
});
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.
注意:Array.prototype.forEach()不是严格意义上的函数方式,因为作为输入参数的函数不应该返回一个值,因此不能将其视为纯函数。
2. Check if any of the elements in an array pass a test
const people = [
{name: 'John', age: 23},
{name: 'Andrew', age: 3},
{name: 'Peter', age: 8},
{name: 'Hanna', age: 14},
{name: 'Adam', age: 37}];
const anyAdult = people.some(person => person.age >= 18);
console.log(anyAdult); // true
3. Transform to a new array
const myArray = [{x:100}, {x:200}, {x:300}];
const newArray= myArray.map(element => element.x);
console.log(newArray); // [100, 200, 300]
Note: The map() method creates a new array with the results of calling a provided function on every element in the calling array.
注意:map()方法创建一个新的数组,其结果是调用调用数组中的每个元素的函数。
4. Sum up a particular property, and calculate its average
const myArray = [{x:100}, {x:200}, {x:300}];
const sum = myArray.map(element => element.x).reduce((a, b) => a + b, 0);
console.log(sum); // 600 = 0 + 100 + 200 + 300
const average = sum / myArray.length;
console.log(average); // 200
5. Create a new array based on the original but without modifying it
const myArray = [{x:100}, {x:200}, {x:300}];
const newArray= myArray.map(element => {
return {
...element,
x: element.x * 2
};
});
console.log(myArray); // [100, 200, 300]
console.log(newArray); // [200, 400, 600]
6. Count the number of each category
const people = [
{name: 'John', group: 'A'},
{name: 'Andrew', group: 'C'},
{name: 'Peter', group: 'A'},
{name: 'James', group: 'B'},
{name: 'Hanna', group: 'A'},
{name: 'Adam', group: 'B'}];
const groupInfo = people.reduce((groups, person) => {
const {A = 0, B = 0, C = 0} = groups;
if (person.group === 'A') {
return {...groups, A: A + 1};
} else if (person.group === 'B') {
return {...groups, B: B + 1};
} else {
return {...groups, C: C + 1};
}
}, {});
console.log(groupInfo); // {A: 3, C: 1, B: 2}
7. Retrieve a subset of an array based on particular criteria
const myArray = [{x:100}, {x:200}, {x:300}];
const newArray = myArray.filter(element => element.x > 250);
console.log(newArray); // [{x:300}]
Note: The filter() method creates a new array with all elements that pass the test implemented by the provided function.
注意:filter()方法创建了一个新的数组,其中包含了通过提供的函数实现的测试的所有元素。
8. Sort an array
const people = [
{ name: "John", age: 21 },
{ name: "Peter", age: 31 },
{ name: "Andrew", age: 29 },
{ name: "Thomas", age: 25 }
];
let sortByAge = people.sort(function (p1, p2) {
return p1.age - p2.age;
});
console.log(sortByAge);
References
- Array.prototype.some()
- Array.prototype.some()
- Array.prototype.forEach()
- Array.prototype.forEach()
- Array.prototype.map()
- Array.prototype.map()
- Array.prototype.filter()
- Array.prototype.filter()
- Array.prototype.sort()
- Array.prototype.sort()
- Spread syntax
- 传播的语法
#27
6
Sure it's inefficient and many despise it, but it's one of the closest to the mentioned:
当然,它是低效的,许多人轻视它,但它是最接近提到的:
var myStringArray = ["Hello","World"];
myStringArray.forEach(function(f){
// Do something
})
#28
6
If you want to use jQuery, it has a nice example in its documentation:
如果您想使用jQuery,它在文档中有一个很好的例子:
$.each([ 52, 97 ], function( index, value ) {
alert( index + ": " + value );
});
#29
5
Well, how about this:
那么,这个怎么样:
for (var key in myStringArray) {
console.log(myStringArray[key]);
}
#30
5
var myStringArray = ["hello", "World"];
myStringArray.forEach(function(val, index){
console.log(val, index);
})