markdown for / forEach / for ... in,什么是最好的?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了markdown for / forEach / for ... in,什么是最好的?相关的知识,希望对你有一定的参考价值。

Ways of looping through Arrays in ES5:

```javascript
let array = [1,2,3];
```

### Clasic for loop

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

### Array.forEach method

```javascript
array.forEach(function (value) {
  console.log(value);
});
```

Downsides: 
- You can’t break out of this loop using a break statement or move to the next iteration with continue.
 
- You can’t return from the enclosing function using a return statement.


### For In

The for-in loop is designed for iterating over an objects properties, like so:

```javascript
var obj = {a:1,b:2};
for (let prop in obj) {
    console.log(prop); //prints a, b
}
```

If we tried to use it with an array:

```javascript
let array = [10,20,30];
for (let index in array) {
  console.log(index); // prints '0', '1' ... converts the index to a string
});
```

In ES6 we have a new syntax:

### For Of

The for–of loop is for looping over the values in an array. It also works on most array-like objects including the new Set and Map types.

```javascript
let array = [10,20,30];
for (var value of array) {
  console.log(value); // prints 10, 20, 30
}
```

- This is the most concise way of looping through array elements.  
- It avoids all the pitfalls of for–in.  
- It works with break, continue, and return  

以上是关于markdown for / forEach / for ... in,什么是最好的?的主要内容,如果未能解决你的问题,请参考以下文章

for、while、foreach性能比较

foreach和for的区别

c# for和foreach哪个执行效率

foreach(增强for循环)和for的区别

for循环 switch foreach用法合区别

php foreach为啥比for效率高