在 JavaScript 中循环遍历数组

发布于 2024-09-04 19:58:08 字数 215 浏览 9 评论 0 原文

在 Java 中,您可以使用 for 循环来遍历数组中的对象,如下所示:

String[] myStringArray = {"Hello", "World"};
for (String s : myStringArray) {
    // Do something
}

我可以在 JavaScript 中执行相同的操作吗?

In Java, you can use a for loop to traverse objects in an array as follows:

String[] myStringArray = {"Hello", "World"};
for (String s : myStringArray) {
    // Do something
}

Can I do the same in JavaScript?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(30

原谅我要高飞 2024-09-11 19:58:10

我认为最好的方法是使用 Array.forEach 函数。如果你不能使用它,我建议从 MDN 获取 polyfill。为了使其可用,这无疑是在 JavaScript 中迭代数组的最安全方法。

Array.prototype.forEach()

正如其他人所建议的,这几乎总是您想要的:

var numbers = [1,11,22,33,44,55,66,77,88,99,111];
var sum = 0;
numbers.forEach(function(n){
  sum += n;
});

这确保您在处理数组的范围内所需的任何内容都保留在该范围内,并且您只处理数组的值,不是对象属性和其他成员,这就是 for .. in 的作用。

在大多数情况下,使用常规 C 风格的 for 循环是可行的。重要的是要记住循环中的所有内容都与程序的其余部分共享其作用域,{} 不会创建新的作用域。

因此:

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);

将输出“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:

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 its scope with the rest of your program, the { } does not create a new scope.

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.

A working jsFiddle example:
https://jsfiddle.net/workingClassHacker/pxpv2dh5/7/

来日方长 2024-09-11 19:58:10

如果你想使用 jQuery,它的文档中有一个很好的例子:

 $.each([ 52, 97 ], function( index, value ) {
      alert( index + ": " + value );
 });

If you want to use jQuery, it has a nice example in its documentation:

 $.each([ 52, 97 ], function( index, value ) {
      alert( index + ": " + value );
 });
挽袖吟 2024-09-11 19:58:10

它不是 100% 相同,但相似:

   var myStringArray = ['Hello', 'World']; // The array uses [] not {}
    for (var i in myStringArray) {
        console.log(i + ' -> ' + myStringArray[i]); // i is the index/key, not the item
    }

It's not 100% identical, but similar:

   var myStringArray = ['Hello', 'World']; // The array uses [] not {}
    for (var i in myStringArray) {
        console.log(i + ' -> ' + myStringArray[i]); // i is the index/key, not the item
    }

爱冒险 2024-09-11 19:58:10

例如,我在 Firefox 控制台中使用:

[].forEach.call(document.getElementsByTagName('pre'), function(e){ 
   console.log(e);
})

您可以使用 querySelectorAll 来获得相同的结果

document.querySelectorAll('pre').forEach( (e) => { 
   console.log(e.textContent);
})
<pre>text 1</pre>
<pre>text 2</pre>
<pre>text 3</pre>

For example, I used in a Firefox console:

[].forEach.call(document.getElementsByTagName('pre'), function(e){ 
   console.log(e);
})

You can use querySelectorAll to get same result

document.querySelectorAll('pre').forEach( (e) => { 
   console.log(e.textContent);
})
<pre>text 1</pre>
<pre>text 2</pre>
<pre>text 3</pre>

隱形的亼 2024-09-11 19:58:09

Opera、Safari、Firefox 和 Chrome 现在都共享一组增强的数组方法,用于优化许多常见循环。

您可能不需要全部,但它们可能非常有用,或者如果每个浏览器都支持它们,它们就会非常有用。

Mozilla Labs 发布了他们和 WebKit 都使用的算法,以便您可以自己添加它们。

过滤器返回满足某些条件或测试的项目数组。

如果每个数组成员都通过测试,every 返回 true。

如果有通过测试,some 返回 true。

forEach 对每个数组成员运行一个函数,并且不返回任何内容。

ma​​p 与 forEach 类似,但它返回每个元素的操作结果的数组。

这些方法都采用一个函数作为其第一个参数,并具有一个可选的第二个参数,该参数是一个对象,当数组成员循环遍历该函数时,您希望将其作用域施加到数组成员上。

忽略它直到你需要它。

indexOflastIndexOf 查找与其参数完全匹配的第一个或最后一个元素的适当位置。

(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;
})();

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.

(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;
})();
又怨 2024-09-11 19:58:09

简介

自上大学以来,我一直使用 Java、JavaScript、Pascal、ABAP、PHP 进行编程、Progress 4GL、C/C++ 以及可能还有一些我现在想不到的其他语言。

虽然它们都有自己的语言特质,但每种语言都有许多相同的基本概念。这些概念包括过程/函数、IF 语句、FOR 循环和 WHILE 循环。


传统的 for 循环

传统的 for 循环包含三个组件:

  1. 初始化: 在第一次执行 Look 块之前执行
  2. 条件:每次执行循环块之前检查一个条件,如果为假则退出循环
  3. 事后思考:每次循环块执行之后执行

这三个组件是分开的彼此之间通过 ; 符号。这三个组件的内容都是可选的,这意味着以下是可能的最小 for 循环:

for (;;) {
    // Do stuff
}

当然,您需要包含一个 if(condition === true) { 休息; }if(condition === true) { return; } 位于 for 循环内的某处以使其停止运行。

不过,通常情况下,初始化用于声明索引,条件用于将该索引与最小值或最大值进行比较,事后用于增加索引:

for (var i = 0, length = 10; i < length; i++) {
    console.log(i);
}

使用传统的 for 循环循环遍历数组 循环

遍历数组的传统方法是这样的:

for (var i = 0, length = myArray.length; i < length; i++) {
    console.log(myArray[i]);
}

或者,如果您喜欢向后循环,则可以这样做:

for (var i = myArray.length - 1; i > -1; i--) {
    console.log(myArray[i]);
}

但是,可能有许多变体,例如这个:

for (var key = 0, value = myArray[key], length = myArray.length; key < length; value = myArray[++key]) {
    console.log(value);
}

...或这个一个...

var i = 0, length = myArray.length;
for (; i < length;) {
    console.log(myArray[i]);
    i++;
}

...或这个:

var key = 0, value;
for (; value = myArray[key++];){
    console.log(value);
}

无论哪种效果最好,很大程度上取决于个人品味和您正在实施的具体用例。

请注意,所有浏览器都支持这些变体,包括非常非常旧的浏览器!


while 循环

for 循环的一种替代方法是 while 循环。要循环遍历数组,您可以这样做:

var key = 0;
while(value = myArray[key++]){
    console.log(value);
}

与传统的 for 循环一样,while 循环甚至受到最古老的浏览器的支持。

另请注意,每个 while 循环都可以重写为 for 循环。例如,上面的 while 循环的行为与 for 循环完全相同:

for(var key = 0; value = myArray[key++];){
    console.log(value);
}

For...in 和 for。 ..of

在 JavaScript 中,您也可以这样做:

for (i in myArray) {
    console.log(myArray[i]);
}

但是,应谨慎使用,因为它在所有情况下的行为都与传统的 for 循环不同,并且需要考虑潜在的副作用。请参阅为什么使用“ for...in" 对于数组迭代是一个坏主意吗? 了解更多详细信息。

作为 for...in,现在还有 for...of。以下示例显示了 for...of 循环和 for...in 循环之间的区别:

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
}

此外,您需要考虑没有任何版本的 Internet Explorer 支持for...of (Edge 12+ 确实),并且 for...in 至少需要 Internet Explorer 10。


Array.prototype.forEach()

for-loops 的替代方案是 Array.prototype.forEach(),使用以下语法:

myArray.forEach(function(value, key, myArray) {
    console.log(value);
});

<所有现代浏览器以及 Internet Explorer 9 及更高版本都支持 code>Array.prototype.forEach()。


最后,许多实用程序库也有自己的 foreach 变体。 AFAIK,最流行的三个是:

jQuery.each(),在 jQuery 中:

$.each(myArray, function(key, value) {
    console.log(value);
});

_.each(),位于 Underscore.js

_.each(myArray, function(value, key, myArray) {
    console.log(value);
});

<强>_.forEach(),在Lodash

_.forEach(myArray, function(value, key) {
    console.log(value);
});

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, and WHILE-loops.


A traditional for-loop

A traditional for loop has three components:

  1. The initialization: executed before the look block is executed the first time
  2. The condition: checks a condition every time before the loop block is executed, and quits the loop if false
  3. 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:

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.

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:

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:

var key = 0;
while(value = myArray[key++]){
    console.log(value);
}

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, the while loop hereabove behaves the exact same way as this for-loop:

for(var key = 0; value = myArray[key++];){
    console.log(value);
}

For...in and for...of

In JavaScript, you can also do this:

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" for array iteration a bad idea? for more details.

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:

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.


Array.prototype.forEach()

An alternative to for-loops is Array.prototype.forEach(), which uses the following syntax:

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.


Libraries

Finally, many utility libraries also have their own foreach variation. AFAIK, the three most popular ones are these:

jQuery.each(), in jQuery:

$.each(myArray, function(key, value) {
    console.log(value);
});

_.each(), in Underscore.js:

_.each(myArray, function(value, key, myArray) {
    console.log(value);
});

_.forEach(), in Lodash:

_.forEach(myArray, function(value, key) {
    console.log(value);
});
苄①跕圉湢 2024-09-11 19:58:09

使用 while 循环...

var i = 0, item, items = ['one', 'two', 'three'];
while(item = items[i++]){
    console.log(item);
}

它记录:“一”、“二”和“三”

对于相反的顺序,一个更高效的循环:

var items = ['one', 'two', 'three'], i = items.length;
while(i--){
    console.log(items[i]);
}

它记录:“三”、“二” ', 和 'one'

或者经典的 for 循环:

var items = ['one', 'two', 'three']
for(var i=0, l = items.length; i < l; i++){
    console.log(items[i]);
}

它记录:'one','two','third'

参考:Google Closure:如何不编写 JavaScript

Use the while loop...

var i = 0, item, items = ['one', 'two', 'three'];
while(item = items[i++]){
    console.log(item);
}

It logs: 'one', 'two', and 'three'

And for the reverse order, an even more efficient loop:

var items = ['one', 'two', 'three'], i = items.length;
while(i--){
    console.log(items[i]);
}

It logs: 'three', 'two', and 'one'

Or the classical for loop:

var items = ['one', 'two', 'three']
for(var i=0, l = items.length; i < l; i++){
    console.log(items[i]);
}

It logs: 'one','two','three'

Reference: Google Closure: How not to write JavaScript

忱杏 2024-09-11 19:58:09

如果您想要一种简洁的方式来编写快速循环,您可以反向迭代:

for (var i=myArray.length;i--;){
  var item=myArray[i];
}

这具有缓存长度的好处(类似于 for (var i=0, len=myArray. length; ifor (var i=0; i) 不同,但需要输入的字符较少。

甚至有时您应该反向迭代,例如迭代 实时 NodeList< /a> 您计划在迭代期间从 DOM 中删除项目。

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.

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.

辞慾 2024-09-11 19:58:09

JavaScript 中以函数式编程方式循环遍历数组的一些用例:

1. 仅循环遍历数组

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
});

注意:严格来说 Array.prototype.forEach() 并不是一种函数式方式,因为该函数它的输入参数不应该返回值,因此不能被视为纯函数。

2. 检查数组中的任何元素是否通过测试

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. 转换为新数组

const myArray = [{x:100}, {x:200}, {x:300}];

const newArray= myArray.map(element => element.x);
console.log(newArray); // [100, 200, 300]

注意:map() 方法创建一个新数组,其中包含对调用数组中的每个元素调用所提供函数的结果。

4. 对特定属性求和,并计算其平均值

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. 基于原始数组创建一个新数组,但不对其进行修改

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. 计算每个类别的数量

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. 根据特定条件检索数组的子集

const myArray = [{x:100}, {x:200}, {x:300}];

const newArray = myArray.filter(element => element.x > 250);
console.log(newArray); // [{x:300}] 

注意:过滤器() 方法创建一个新数组,其中包含通过所提供函数实现的测试的所有元素。

8. 对数组进行排序

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);

在此处输入图像描述

9. 在数组中查找元素

const people = [ {name: "john", age:23},
                {name: "john", age:43},
                {name: "jim", age:101},
                {name: "bob", age:67} ];

const john = people.find(person => person.name === 'john');
console.log(john);

在此处输入图像描述

Array.prototype.find() 方法返回数组中满足所提供的第一个元素的值测试功能。

参考文献

Some use cases of looping through an array in the functional programming way in 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.

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.

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.

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);

enter image description here

9. Find an element in an array

const people = [ {name: "john", age:23},
                {name: "john", age:43},
                {name: "jim", age:101},
                {name: "bob", age:67} ];

const john = people.find(person => person.name === 'john');
console.log(john);

enter image description here

The Array.prototype.find() method returns the value of the first element in the array that satisfies the provided testing function.

References

鹿童谣 2024-09-11 19:58:09

是的,您可以在 JavaScript 中使用循环执行相同的操作,但不限于。在 JavaScript 中,有多种方法可以对数组进行循环。想象一下下面有这个数组,并且您想对其进行循环:

var arr = [1, 2, 3, 4, 5];

这些是解决方案:

1) For 循环

for 循环是一种常见的循环方式在 JavaScript 中通过数组,但它不被认为是大型数组最快的解决方案:

for (var i=0, l=arr.length; i<l; i++) {
  console.log(arr[i]);
}

2) While 循环

while 循环被认为是循环遍历长数组的最快方式,但通常较少使用在 JavaScript 代码中:

let i=0;

while (arr.length>i) {
    console.log(arr[i]);
    i++;
}

3) Do while
do whilewhile 执行相同的操作,但有一些语法差异,如下所示:

let i=0;
do {
  console.log(arr[i]);
  i++;
}
while (arr.length>i);

这些是执行 JavaScript 循环的主要方法,但还有其他几种方法可以执行那。

我们还使用 for in 循环来循环 JavaScript 中的对象。

另请查看 JavaScript 中数组上的 map()filter()reduce() 等函数。它们可能比使用 whilefor 做得更快更好。

如果您想了解有关 JavaScript 中数组的异步函数的更多信息,这是一篇很好的文章。

函数式编程在业界引起了不小的轰动
如今的发展世界。有充分的理由:功能性
技术可以帮助您编写更易于编写的声明性代码
一目了然、重构、测试。

函数式编程的基石之一是它的特殊用途
列表和列表操作。这些东西正是
听起来就像是:事物的数组,以及你对它们所做的事情。
但功能性思维对待他们的方式与对待你有点不同
可能会期待。

本文将仔细研究我所说的“大
三个“列表操作:map、filter 和reduce。绞尽脑汁
围绕这三个功能是迈向能够
编写干净的功能代码,并打开通往广阔领域的大门
函数式和反应式编程的强大技术。

这也意味着您再也不必编写 for 循环。

了解更多>> 此处

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:

var arr = [1, 2, 3, 4, 5];

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:

for (var i=0, l=arr.length; i<l; i++) {
  console.log(arr[i]);
}

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:

let i=0;

while (arr.length>i) {
    console.log(arr[i]);
    i++;
}

3) Do while
A do while is doing the same thing as while with some syntax difference as below:

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 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 using while and for.

This is a good article if you like to learn more about the asynchronous functions over arrays in JavaScript.

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.

It also means you'll never have to write a for loop again.

Read more>> here:

冬天旳寂寞 2024-09-11 19:58:09

有一种方法可以做到这一点,即循环中的隐式作用域非常小,并且不需要额外的变量。

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.
}

或者,如果您确实想获取 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
}

现代浏览器都支持迭代器方法 forEachmapreducefilter 以及 数组原型

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:

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.

柳若烟 2024-09-11 19:58:09

JavaScript 中有多种循环数组的方法。

通用循环:

var i;
for (i = 0; i < substr.length; ++i) {
    // Do something with `substr[i]`
}

ES5 的 forEach:

substr.forEach(function(item) {
    // Do something with `item`
});

jQuery.each:

jQuery.each(substr, function(index, item) {
    // Do something with `item` (or `this` is also `item` if you like)
});

看看 了解详细信息,或者您也可以查看MDN 用于在 JavaScript 和 JavaScript 中循环遍历数组使用 jQuery 检查 每个 jQuery

There are various way to loop through array in JavaScript.

Generic loop:

var i;
for (i = 0; i < substr.length; ++i) {
    // Do something with `substr[i]`
}

ES5's forEach:

substr.forEach(function(item) {
    // Do something with `item`
});

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.

昨迟人 2024-09-11 19:58:09

数组循环:

for(var i = 0; i < things.length; i++){
    var thing = things[i];
    console.log(thing);
}

对象循环:

for(var prop in obj){
    var propValue = obj[prop];
    console.log(propValue);
}

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);
}
好听的两个字的网名 2024-09-11 19:58:09

我强烈建议使用 Underscore.js 库。它为您提供了各种可用于迭代数组/集合的函数。

例如:

_.each([1, 2, 3], function(num){ alert(num); });
=> alerts each number in turn...

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:

_.each([1, 2, 3], function(num){ alert(num); });
=> alerts each number in turn...
雨轻弹 2024-09-11 19:58:09

如果有人对可用于数组迭代的多种机制的性能方面感兴趣,我准备了以下 JSPerf 测试:

https://jsperf.com/fastest-array-iterator

Performance results

结果:

传统的 for() 迭代器是迄今为止最快的方法,尤其是与缓存的数组长度

let arr = [1,2,3,4,5];

for(let i=0, size=arr.length; i<size; i++){
    // Do something
}

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

Performance results

Results:

The traditional for() iterator, is by far the fastest method, especially when used with the array length cached.

let arr = [1,2,3,4,5];

for(let i=0, size=arr.length; i<size; i++){
    // Do something
}

The Array.prototype.forEach() and the Array.prototype.map() methods are the slowest approximations, probably as a consequence of the function call overhead.

吾性傲以野 2024-09-11 19:58:09

如果您使用 jQuery 库,请考虑使用
http://api.jquery.com/jQuery.each/

从文档中:

jQuery.each(集合,回调(indexInArray,valueOfElement))

返回: 对象

描述: 通用迭代器函数,可用于
无缝迭代对象和数组。数组和类数组
具有长度属性的对象(例如函数的参数对象)
按数字索引迭代,从 0 到 length-1。其他对象是
通过其命名属性进行迭代。

$.each() 函数与 $(selector).each() 不同,后者是
用于专门迭代 jQuery 对象。 $.each()
函数可用于迭代任何集合,无论它是一个
映射(JavaScript 对象)或数组。对于数组来说,
回调传递一个数组索引和一个相应的数组值
时间。 (该值也可以通过 this 关键字访问,但是
Javascript 始终会将 this 值包装为 Object,即使它是
一个简单的字符串或数字值。)该方法返回其第一个
参数,被迭代的对象。

If you're using the jQuery library, consider using
http://api.jquery.com/jQuery.each/

From the documentation:

jQuery.each( collection, callback(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.

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 the this keyword, but
Javascript will always wrap the this value as an Object even if it is
a simple string or number value.) The method returns its first
argument, the object that was iterated.

隔岸观火 2024-09-11 19:58:09

我还没有看到这种变化,我个人最喜欢它:

给定一个数组:

var someArray = ["some", "example", "array"];

您可以循环它而无需访问 length 属性:

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);
}

请参阅此 JsFiddle 演示: http://jsfiddle.net/prvzk/

这仅适用于稀疏的数组。这意味着数组中的每个索引实际上都有一个值。然而,我发现实际上我很少在 JavaScript 中使用稀疏数组......在这种情况下,使用对象作为映射/哈希表通常要容易得多。如果您确实有一个稀疏数组,并且想要循环 0 .. length-1,则需要 for (var i=0; i if 在循环内检查当前索引处的元素是否实际定义。

另外,正如 CMS 在下面的评论中提到的,您只能在不包含任何虚假值的数组上使用它。示例中的字符串数组可以工作,但如果有空字符串、0 或 NaN 等数字,则循环将提前中断。同样,在实践中,这对我来说几乎不是问题,但需要记住这一点,这使得在使用它之前需要考虑一个循环......这可能会取消某些人的资格:)

我喜欢这个的原因循环是:

  • 写起来很短
  • 不需要访问(更不用说缓存)长度属性
  • 要访问的项目在循环内自动定义
    身体在您选择的名字下。
  • 与 array.push 和 array.splice 非常自然地结合使用列表/堆栈等数组。

这样做的原因是数组规范要求当您从索引 >= 数组长度读取项目时,它将返回 undefined。当您写入这样的位置时,它实际上会更新长度。

对我来说,这个构造最接近地模拟了我喜欢的 Java 5 语法:

for (String item : someArray) {
}

...还有一个额外的好处,就是还可以了解循环内的当前索引

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/

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:

  • 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

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:

for (String item : someArray) {
}

... with the added benefit of also knowing about the current index inside the loop

小红帽 2024-09-11 19:58:09

数组迭代有 4 种方式:

// 1: for

for (let i = 0; i < arr.length; ++i) {
  console.log(arr[i]);
}

// 2: forEach

arr.forEach((v, i) => console.log(v));

// 3: for in

for (let i in arr) {
  console.log(arr[i]);
}

// 4: for of

for (const v of arr) {
  console.log(v);
}

摘要:1 和 3 解决方案创建额外的变量,2 - 创建额外的函数上下文。 最好的方法是第四种 - “for of”

There are 4 ways of array iteration:

// 1: for

for (let i = 0; i < arr.length; ++i) {
  console.log(arr[i]);
}

// 2: forEach

arr.forEach((v, i) => console.log(v));

// 3: for in

for (let i in arr) {
  console.log(arr[i]);
}

// 4: for of

for (const v of arr) {
  console.log(v);
}

Summary: 1 and 3 solutions create extra variable, 2 - create extra function context. The best way is 4th - "for of".

画▽骨i 2024-09-11 19:58:09

深奥的

let a= ["Hello", "World"];

while(a.length) { console.log( a.shift() ); }

性能测试

今天(2022-11-13)我在 Chrome 107、Safari 15.2 和 Firefox 106 上对所选解决方案进行了测试。

结论

  • 解决方案 C 和 D 在所有浏览器上针对所有阵列都很快或最快。
  • 解决方案 A 和 B 在所有浏览器上对于所有数组都是最慢的

结果

在此处输入图像描述

详细信息

我执行 3 个测试:

  • 小 - 对于 2 元素数组(如 OP) - 您可以运行它 此处
  • 中 - 对于 10K 元素数组 - 您可以运行它 这里
  • big - 对于 100K 元素数组 - 你可以在这里运行它

下面的代码片段展示了测试中使用的代码。

function A(a) {
  let r=0;
  while(a.length) r+= a.shift().length;
  return r;
}

function B(a) {
  let r=0;
  for(i in a) r+= a[i].length;
  return r;
}

function C(a) {
  let r=0;
  for(x of a) r+= x.length;
  return r;
}

function D(a) {
  let r=0;
  for (i=0; i<a.length; ++i) r+= a[i].length;
  return r;

}

function E(a) {
  let r=0;
  a.forEach(x=> r+= x.length);
  return r;
}

let arr= ["Hello", "World!"];
[A,B,C,D,E].forEach(f => console.log(`${f.name}: ${f([...arr])}`))

以下是 Chrome 对于中等数组的结果示例:

在此处输入图像描述

Esoteric

let a= ["Hello", "World"];

while(a.length) { console.log( a.shift() ); }

Performance test

Today (2022-11-13) I perform a test on Chrome 107, Safari 15.2 and Firefox 106 on chosen solutions.

Conclusions

  • solutions C and D are fast or fastest on all browsers for all arrays.
  • solution A and B are slowest on all browsers for all arrays

Results

enter image description here

Details

I perform 3 tests:

  • small - for 2 elements array (like OP) - you can run it here
  • medium - for 10K elements array and - you can run it here
  • big - for 100K elements array - you can run it here

The below snippet presents code used in the test.

function A(a) {
  let r=0;
  while(a.length) r+= a.shift().length;
  return r;
}

function B(a) {
  let r=0;
  for(i in a) r+= a[i].length;
  return r;
}

function C(a) {
  let r=0;
  for(x of a) r+= x.length;
  return r;
}

function D(a) {
  let r=0;
  for (i=0; i<a.length; ++i) r+= a[i].length;
  return r;

}

function E(a) {
  let r=0;
  a.forEach(x=> r+= x.length);
  return r;
}

let arr= ["Hello", "World!"];
[A,B,C,D,E].forEach(f => console.log(`${f.name}: ${f([...arr])}`))

Here are example results for Chrome for a medium array:

enter image description here

叫思念不要吵 2024-09-11 19:58:09

有一种方法可以只迭代自己的对象属性,不包括原型的属性:

for (var i in array) if (array.hasOwnProperty(i)) {
    // Do something with array[i]
}

但它仍然会迭代自定义属性。

在 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:

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 an array.

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.

软糖 2024-09-11 19:58:09

最优雅、最快速的方式

var arr = [1, 2, 3, 1023, 1024];
for (var value; value = arr.pop();) {
    value + 1
}

http://jsperf.com/native-loop-performance/8


已编辑(因为我错了)


比较循环遍历 100000 个项目的数组的方法,并每次对新值执行最小操作。

准备:

<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>

测试:

<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>

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


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:

<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>
黑色毁心梦 2024-09-11 19:58:09

在 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>

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 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>

怎樣才叫好 2024-09-11 19:58:09

优化的方法是缓存数组的长度并使用单变量模式,使用单个 var 关键字初始化所有变量。

var i, max, myStringArray = ["Hello", "World"];
for (i = 0, max = myStringArray.length; i < max; i++) {
    alert(myStringArray[i]);

    // Do something
}

如果迭代的顺序并不重要,那么您应该尝试反向循环。它是最快的,因为它减少了条件测试的开销,并且减量在一个语句中:

var i,myStringArray = ["item1","item2"];
for (i =  myStringArray.length; i--) {
    alert(myStringArray[i]);
}

或者使用 while 循环更好、更干净:

var myStringArray = ["item1","item2"],i = myStringArray.length;
while(i--) {
   // Do something with fruits[i]
}

The optimized approach is to cache the length of array and using the single variable pattern, initializing all variables with a single var keyword.

var i, max, myStringArray = ["Hello", "World"];
for (i = 0, max = myStringArray.length; i < max; i++) {
    alert(myStringArray[i]);

    // Do something
}

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:

var i,myStringArray = ["item1","item2"];
for (i =  myStringArray.length; i--) {
    alert(myStringArray[i]);
}

Or better and cleaner to use a while loop:

var myStringArray = ["item1","item2"],i = myStringArray.length;
while(i--) {
   // Do something with fruits[i]
}
可是我不能没有你 2024-09-11 19:58:09

在 JavaScript 中,有很多循环数组的解决方案。

下面的代码是流行的

/** 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()

In JavaScript, there are so many solutions to loop an array.

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()

金橙橙 2024-09-11 19:58:08

三个主要选项:

  1. for (var i = 0; i < xs.length; i++) { console.log(xs[i]); }
  2. xs.forEach((x, i) => console.log(x));
  3. for (const x of xs) { console.log(x); }

详细示例如下。


1. 顺序 for 循环:

var myStringArray = ["Hello","World"];
var arrayLength = myStringArray.length;
for (var i = 0; i < arrayLength; i++) {
    console.log(myStringArray[i]);
    //Do something
}

优点

  • 适用于各种环境
  • 您可以使用 breakcontinue 流程控制语句

缺点

  • 过于冗长
  • 命令式
  • 易于使用 < a href="https://en.wikipedia.org/wiki/Off-by-one_error#Looping_over_arrays" rel="noreferrer">差一错误(有时也称为栅栏柱错误)

2. Array.prototype.forEach

ES5 规范引入了很多有益的数组方法。其中之一是 Array.prototype .forEach 为我们提供了一种迭代数组的简洁方法:

const array = ["one", "two", "three"]
array.forEach(function (item, index) {
  console.log(item, index);
});

ES5 规范发布(2009 年 12 月)已近十年,它已被桌面、服务器和移动环境中的几乎所有现代引擎实现,因此使用它们是安全的。

使用 ES6 箭头函数语法,它更加简洁:

array.forEach(item => console.log(item));

箭头函数也被广泛实现,除非您计划支持古老的平台(例如,Internet Explorer 11);你也可以安全离开了。

优点

  • 非常简短。
  • 声明式

缺点

  • 不能使用break / continue

通常,您可以通过过滤来代替 break 脱离命令式循环的需要迭代数组元素之前,例如:

array.filter(item => item.condition < 10)
     .forEach(item => console.log(item))

请记住,如果您要迭代数组以从中构建另一个数组,则应使用 map。我已经多次看到这种反模式。

反模式:

const numbers = [1,2,3,4,5], doubled = [];

numbers.forEach((n, i) => { doubled[i] = n * 2 });

地图的正确用例:

const numbers = [1,2,3,4,5];
const doubled = numbers.map(n => n * 2);

console.log(doubled);

另外,如果您尝试将数组减少为一个值,例如,您想要对数字数组求和,则应该使用reduce方法。

反模式:

const numbers = [1,2,3,4,5];
const sum = 0;
numbers.forEach(num => { sum += num });

正确使用reduce

const numbers = [1,2,3,4,5];
const sum = numbers.reduce((total, n) => total + n, 0);

console.log(sum);

3. ES6 for-of 语句:

ES6 标准引入了可迭代对象的概念,并定义了一种用于遍历数据的新结构,即 for...of 语句。

此语句适用于任何类型的可迭代对象,也适用于生成器(任何具有 \[Symbol.iterator\] 属性)。

根据定义,数组对象是 ES6 中内置的可迭代对象,因此您可以对它们使用以下语句:

let colors = ['red', 'green', 'blue'];
for (const color of colors){
    console.log(color);
}

优点

  • 它可以迭代多种对象。
  • 可以使用普通的流程控制语句(break / continue)。
  • 对于迭代串行异步值很有用。

缺点

不要使用 for...in

@zipcodeman 建议使用 for...in 语句,但用于迭代数组 for-in应避免,该语句旨在枚举对象属性。

它不应该用于类似数组的对象,因为:

  • 不能保证迭代的顺序;数组索引可能无法按数字顺序访问。
  • 继承的属性也被枚举。

第二点是它会给你带来很多问题,例如,如果你扩展 Array.prototype 对象以包含其中的方法,那么该属性也将被枚举。

例如:

Array.prototype.foo = "foo!";
var array = ['a', 'b', 'c'];

for (var i in array) {
    console.log(array[i]);
}

上面的代码将控制台日志“a”、“b”、“c”和“foo!”。

如果您使用一些严重依赖本机原型增强的库(例如 MooTools)。

正如我之前所说,for-in 语句是用来枚举对象属性的,例如:

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...
        console.log("prop: " + prop + " value: " + obj[prop])
    }
}

在上面的示例中,hasOwnProperty 方法允许您仅枚举自己的属性。就是这样,只有对象物理上具有的属性,没有继承的属性。

我建议您阅读以下文章:

Three main options:

  1. for (var i = 0; i < xs.length; i++) { console.log(xs[i]); }
  2. xs.forEach((x, i) => console.log(x));
  3. for (const x of xs) { console.log(x); }

Detailed examples are below.


1. Sequential for loop:

var myStringArray = ["Hello","World"];
var arrayLength = myStringArray.length;
for (var i = 0; i < arrayLength; i++) {
    console.log(myStringArray[i]);
    //Do something
}

Pros

  • Works on every environment
  • You can use break and continue flow control statements

Cons

  • Too verbose
  • Imperative
  • Easy to have off-by-one errors (sometimes also called a fence post error)

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:

const array = ["one", "two", "three"]
array.forEach(function (item, index) {
  console.log(item, index);
});

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:

array.forEach(item => console.log(item));

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

  • Very short and succinct.
  • Declarative

Cons

  • Cannot use break / continue

Normally, you can replace the need to break out of imperative loops by filtering the array elements before iterating them, for example:

array.filter(item => item.condition < 10)
     .forEach(item => console.log(item))

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:

const numbers = [1,2,3,4,5], doubled = [];

numbers.forEach((n, i) => { doubled[i] = n * 2 });

Proper use case of map:

const numbers = [1,2,3,4,5];
const doubled = numbers.map(n => n * 2);

console.log(doubled);

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:

const numbers = [1,2,3,4,5];
const sum = 0;
numbers.forEach(num => { sum += num });

Proper use of reduce:

const numbers = [1,2,3,4,5];
const sum = numbers.reduce((total, n) => total + n, 0);

console.log(sum);

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:

let colors = ['red', 'green', 'blue'];
for (const color of colors){
    console.log(color);
}

Pros

  • It can iterate over a large variety of objects.
  • Can use normal flow control statements (break / continue).
  • Useful to iterate serially asynchronous values.

Cons

Do not use for...in

@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.

It shouldn't be used for array-like objects because:

  • 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 also be enumerated.

For example:

Array.prototype.foo = "foo!";
var array = ['a', 'b', 'c'];

for (var i in array) {
    console.log(array[i]);
}

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:

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...
        console.log("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.

I would recommend you to read the following article:

深居我梦 2024-09-11 19:58:08

是的,假设您的实施包括 for...of ECMAScript 2015(“Harmony”版本)……目前这是一个相当安全的假设。

它的工作原理如下:

// REQUIRES ECMASCRIPT 2015+
var s, myStringArray = ["Hello", "World"];
for (s of myStringArray) {
  // ... do something with s ...
}

或者更好,因为 ECMAScript 2015 还提供了块作用域变量:(

// REQUIRES ECMASCRIPT 2015+
const myStringArray = ["Hello", "World"];
for (const s of myStringArray) {
  // ... do something with s ...
}
// s is no longer defined here

变量 s 在每次迭代中都不同,但仍然可以在内部声明 const 关于稀疏数组的

注意事项:JavaScript 中的数组实际上可能不会存储与其 length 报告的一样多的项目;该数字仅比存储值的最高索引大 1。如果数组包含的元素少于其长度所指示的元素,则称其为稀疏。例如,拥有一个仅包含索引 3、12 和 247 处的项目的数组是完全合法的;这样一个数组的长度是 248,尽管它实际上只存储 3 个值。如果您尝试访问任何其他索引处的项目,该数组将显示为具有 undefined 值,但该数组仍然与实际具有 undefined 的数组不同存储的值。您可以通过多种方式看到这种差异,例如 Node REPL 显示数组的方式:

> a              // array with only one item, at index 12
[ <12 empty items>, 1 ]
> a[0]           // appears to have undefined at index 0
undefined
> a[0]=undefined // but if we put an actual undefined there
undefined
> a              // it now looks like this
[ undefined, <11 empty items>, 1 ]

因此,当您想要“循环”数组时,您需要回答一个问题:您想要循环整个范围吗?由其长度指示并处理任何缺失元素的undefined,或者您只想处理实际存在的元素?这两种方法都有很多应用;这仅取决于您使用数组的目的。

如果使用 for..of 迭代数组,则循环体将执行 length 次,并设置循环控制变量对于数组中实际不存在的任何项目,将其设置为 undefined。根据“使用”代码的详细信息,该行为可能是您想要的,但如果不是,您应该使用不同的方法。

当然,一些开发人员别无选择,只能使用不同的方法,因为无论出于何种原因,他们的目标 JavaScript 版本尚不支持 for...of< /代码>。

只要您的 JavaScript 实现符合 ECMAScript 规范的上一版本(例如,排除了 Internet Explorer 9 之前的版本),那么您就可以使用 Array#forEach 迭代器方法而不是一个循环。在这种情况下,您传递一个要在数组中的每个项目上调用的函数:

var myStringArray = [ "Hello", "World" ];
myStringArray.forEach( function(s) { 
     // ... do something with s ...
} );

如果您的实现支持 ES6+,您当然可以使用箭头函数:

myStringArray.forEach( s => { 
     // ... do something with s ...
} );

for...of, .forEach 仅针对数组中实际存在的元素调用该函数。如果传递我们假设的包含三个元素且长度为 248 的数组,它只会调用该函数 3 次,而不是 248 次。如果这就是您想要处理稀疏数组的方式,即使您的解释器支持 for...of.forEach 也可能是可行的方法。

最后一个选项是 所有版本的 JavaScript rel="noreferrer">显式计数循环。您只需从 0 计数到比长度少 1 并使用计数器作为索引即可。基本循环如下所示:

var i, s, myStringArray = [ "Hello", "World" ], len = myStringArray.length;
for (i=0; i<len; ++i) {
  s = myStringArray[i];
  // ... do something with s ...
}

这种方法的一个优点是您可以选择如何处理稀疏数组。上面的代码将运行循环体完整的 length 次,对于任何缺失的元素,将 s 设置为 undefined,就像 >for..of;如果您只想处理稀疏数组中实际存在的元素,例如 .forEach,您可以在索引上添加一个简单的 in 测试:

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 ...
  }
}

具体取决于您的实现优化时,将长度值分配给局部变量(而不是在循环条件中包含完整的 myStringArray.length 表达式)可以显着提高性能,因为它每次都会跳过属性查找。您可能会看到在循环初始化子句中完成的长度缓存,如下所示:

var i, len, myStringArray = [ "Hello", "World" ];
for (len = myStringArray.length, i=0; i<len; ++i) {

显式计数循环还意味着您可以访问每个值的索引(如果您需要的话)。索引还会作为额外参数传递给您传递给 forEach 的函数,因此您也可以通过这种方式访问​​它:

myStringArray.forEach( (s,i) => {
   // ... do something with s and i ...
});

for...of< /code> 不会为您提供与每个对象关联的索引,但只要您要迭代的对象实际上是 Array 的实例(而不是其他可迭代类型之一for..of 有效),您可以使用 Array#entries 方法将其更改为 [index, item] 对的数组,然后对其进行迭代:

for (const [i, s] of myStringArray.entries()) {
  // ... do something with s and i ...
}

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:

// 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:

// REQUIRES ECMASCRIPT 2015+
const myStringArray = ["Hello", "World"];
for (const s of myStringArray) {
  // ... do something with s ...
}
// s is no longer defined here

(The variable s is different on each iteration, but can still be declared const 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; the length 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 the undefined value there, but the array is nonetheless is distinct from one that actually has undefined values stored. You can see this difference in a number of ways, for example in the way the Node REPL displays arrays:

> a              // array with only one item, at index 12
[ <12 empty items>, 1 ]
> a[0]           // appears to have undefined at index 0
undefined
> a[0]=undefined // but if we put an actual undefined there
undefined
> a              // it now looks like this
[ undefined, <11 empty items>, 1 ]

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 undefineds 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 executed length times, and the loop control variable is set to undefined 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:

var myStringArray = [ "Hello", "World" ];
myStringArray.forEach( function(s) { 
     // ... do something with s ...
} );

You can of course use an arrow function if your implementation supports ES6+:

myStringArray.forEach( s => { 
     // ... do something with s ...
} );

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 supports for...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:

var i, s, myStringArray = [ "Hello", "World" ], len = myStringArray.length;
for (i=0; i<len; ++i) {
  s = myStringArray[i];
  // ... do something with s ...
}

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, with s set to undefined for any missing elements, just like for..of; if you instead want to handle only the actually-present elements of a sparse array, like .forEach, you can add a simple in test on the index:

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 ...
  }
}

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:

var i, len, myStringArray = [ "Hello", "World" ];
for (len = myStringArray.length, i=0; i<len; ++i) {

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:

myStringArray.forEach( (s,i) => {
   // ... do something with s and i ...
});

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 of Array (and not one of the other iterable types for..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:

for (const [i, s] of myStringArray.entries()) {
  // ... do something with s and 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 is it guaranteed to iterate over those in numeric order. Therefore, the for...in syntax should not be used for looping through Arrays.

寂寞清仓 2024-09-11 19:58:08

您可以使用 map,这是一种函数式编程技术,也可用于其他语言,例如 PythonHaskell

[1,2,3,4].map( function(item) {
     alert(item);
})

一般语法是:

array.map(func)

一般来说,func 将采用一个参数,该参数是数组的一项。但就 JavaScript 而言,它可以采用第二个参数(即项目的索引)和第三个参数(即数组本身)。

array.map 的返回值是另一个数组,因此您可以像这样使用它:

var x = [1,2,3,4].map( function(item) {return item * 10;});

现在 x 是 [10,20,30,40]

您不必内联编写该函数。它可以是一个单独的函数。

var item_processor = function(item) {
      // Do something complicated to an item
}

new_list = my_list.map(item_processor);

这有点相当于:

 for (item in my_list) {item_processor(item);}

除非你没有得到new_list

You can use map, which is a functional programming technique that's also available in other languages like Python and 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.

The return value of array.map is another array, so you can use it like this:

var x = [1,2,3,4].map( function(item) {return item * 10;});

And now x is [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.

诺曦 2024-09-11 19:58:08

for (const s of myStringArray) {

(直接回答你的问题:现在你可以了!)

大多数其他答案都是正确的,但他们没有提到(截至撰写本文时)ECMAScript  6  ; 2015 引入了一种新的迭代机制,即 for..of 循环。

这种新语法是在 JavaScript 中迭代数组的最优雅的方法(只要不需要迭代索引)。

目前它适用于 Firefox 13+、Chrome 37+,并且本身不支持其他浏览器(请参阅下面的浏览器兼容性)。幸运的是,我们拥有 JavaScript 编译器(例如 Babel),使我们能够使用当今的下一代功能。

它也适用于 Node.js(我在 0.12.0 版本上测试过)。

迭代数组

// You could also use "let" or "const" instead of "var" for block scope.
for (var letter of ["a", "b", "c"]) {
   console.log(letter);
}

迭代对象数组

const band = [
  {firstName : 'John', lastName: 'Lennon'},
  {firstName : 'Paul', lastName: 'McCartney'}
];

for(const member of band){
  console.log(member.firstName + ' ' + member.lastName);
}

迭代生成器:

(示例摘自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 (const n of fibonacci()) {
  console.log(n);
  // Truncate the sequence at 1000
  if (n >= 1000) {
    break;
  }
}

兼容性表:
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  6  2015 is bringing a new mechanism for doing iteration, the for..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

// You could also use "let" or "const" instead of "var" for block scope.
for (var letter of ["a", "b", "c"]) {
   console.log(letter);
}

Iterating an array of objects

const band = [
  {firstName : 'John', lastName: 'Lennon'},
  {firstName : 'Paul', lastName: 'McCartney'}
];

for(const 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)

function* fibonacci() { // A generator function
  let [prev, curr] = [1, 1];
  while (true) {
    [prev, curr] = [curr, prev + curr];
    yield curr;
  }
}

for (const n of fibonacci()) {
  console.log(n);
  // Truncate the sequence at 1000
  if (n >= 1000) {
    break;
  }
}

Compatibility table:
http://kangax.github.io/compat-table/es6/#test-for..of_loops

Specification: http://wiki.ecmascript.org/doku.php?id=harmony:iterators

}

走过海棠暮 2024-09-11 19:58:08

在 JavaScript 中,不建议使用 for-in 循环遍历数组,但最好使用 for 循环,例如:

for(var i=0, len=myArray.length; i < len; i++){}

它也经过优化(“缓存”数组长度)。如果您想了解更多信息,阅读我关于该主题的帖子

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:

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.

甜嗑 2024-09-11 19:58:08

循环数组的 6 种不同方法

您可以通过多种不同的方法循环数组。我从上到下对我最喜欢的 6 种方法进行了排序。

1. 使用 JavaScript for 循环

当只是简单地循环遍历数组时, for 循环是我的第一选择。

let array = [1, 2, 3, 4, 5];
for (let i = 0; i < array.length; i++) {
  console.log(array[i]);
}

2. 使用 forEach 循环

forEach 循环是一种循环遍历数组的现代方法。此外,它还提供了对数组和元素的更大灵活性和控制。

let array = [1, 2, 3, 4, 5];
array.forEach((element) => {
  console.log(element);
});

3. 使用 for...of

for...of 循环可以让您直接访问数组元素。

let array = [1, 2, 3, 4, 5];
for (let element of array) {
  console.log(element);
}

4. 使用 for...in 循环

for...in 为您提供一个可以访问数组元素的键。

let array = [1, 2, 3, 4, 5];
for(let index in array){
  console.log(array[index]);
}

5. 使用while 循环

while 循环也可用于循环数组。

let array = [1, 2, 3, 4, 5];
let length = array.length;
while(length > 0){
  console.log(array[array.length - length]);
  length--;
}

6. 使用 do...while 循环

同样,我使用 do...while 循环

let array = [1, 2, 3, 4, 5];
let length = array.length;
do {
  console.log(array[array.length - length]);
  length--;
}
while (length > 0)

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.

let array = [1, 2, 3, 4, 5];
for (let i = 0; i < array.length; i++) {
  console.log(array[i]);
}

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.

let array = [1, 2, 3, 4, 5];
array.forEach((element) => {
  console.log(element);
});

3. Using for...of

for...of loop gives you direct access to the array elements.

let array = [1, 2, 3, 4, 5];
for (let element of array) {
  console.log(element);
}

4. Using for...in loop

for...in gives you a key using which you can access array elements.

let array = [1, 2, 3, 4, 5];
for(let index in array){
  console.log(array[index]);
}

5. Using while loop

while loop is can be used to loop through the array as well.

let array = [1, 2, 3, 4, 5];
let length = array.length;
while(length > 0){
  console.log(array[array.length - length]);
  length--;
}

6. Using do...while loop

Likewise, I use do...while loop

let array = [1, 2, 3, 4, 5];
let length = array.length;
do {
  console.log(array[array.length - length]);
  length--;
}
while (length > 0)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文