Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
176 views
in Technique[技术] by (71.8m points)

javascript - 遍历JavaScript中的数组(Loop through an array in JavaScript)

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中做同样的事情吗?)

  ask by Mark Szymanski translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You have several options:

(您有几种选择:)

1. Sequential for loop: (1.连续for循环:)

 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

    (您可以使用breakcontinue流控制语句)

Cons

(缺点)

  • Too verbose

    (太冗长)

  • Imperative

    (势在必行)

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

    (容易出现一对一错误 (有时也称为栅栏错误 ))

2. Array.prototype.forEach (2. Array.prototype.forEach)

The ES5 specification introduced a lot of beneficial array methods, one of them, the Array.prototype.forEach and it gives us a concise way to iterate over an array:

(ES5规范引入了许多有益的数组方法,其中之一是Array.prototype.forEach ,它为我们提供了一种遍历数组的简洁方法:)

 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.

(ES5规范发布时(截至2009年12月)已经有将近十年的时间,它已经由台式机,服务器和移动环境中的几乎所有现代引擎实现,因此可以安全地使用它们。)

And with the ES6 arrow function syntax, it's even more succinct:

(借助ES6箭头函数语法,它更加简洁:)

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

Arrow functions are also widely implemented unless you plan to support ancient platforms (eg, IE11);

(除非计划支持古老的平台(例如IE11),否则箭头功能也得到了广泛的实现。)

you are also safe to go.

(你也很安全。)

Pros

(优点)

  • Very short and succinct.

    (非常简短。)

  • Declarative

    (陈述式)

Cons

(缺点)

  • Cannot use break / continue

    (无法使用break / continue)

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

(通常,您可以通过在迭代数组元素之前对其进行过滤来替换break命令式循环的需要,例如:)

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.

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

Anti-pattern:

(反模式:)

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

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

Proper use case of map :

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

(另外,例如,如果您试图将数组缩小为一个值,则想对数字数组求和,则应使用reduce方法。)

Anti-pattern:

(反模式:)

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

Proper use of reduce :

(正确使用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 (3. ES6 for-of声明)

The ES6 standard introduces the concept of iterable objects and defines a new construct for traversing data, the for...of statement.

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

This statement works for any kind of iterable object and also for generators (any object that has a [Symbol.iterator] property).

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

Array objects are by definition built-in iterables in ES6, so you can use this statement on them:

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

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

    (可以使用普通的流控制语句( break / continue )。)

  • Useful to iterate serially asynchronous values.

    (对迭代串行异步值很有用。)

Cons

(缺点)

Do not use for...in (请勿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.

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

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.

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

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!".

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

That be particularly a problem if you use some library that relies heavily on native prototypes augmentation (such as MooTools, for example).

(如果您使用一些严重依赖本机原型扩充的库(例如,MooTools),则这尤其成问题。)

The for-in statement as I said before is there to enumerate object properties, for example:

(我之前说过的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]) } } 

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方法允许您仅枚举自己的属性


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...