成为规范的ES版本
- for...in: ES6之前就出现
- for...of: ES6出现
for...in
MDN介绍:
The for...in statement iterates over all enumerable properties of an object that are keyed by strings (ignoring ones keyed by Symbols), including inherited enumerable properties.
特点:
- properties of an object:for...in遍历的是对象的属性名(不是属性值)。例如:遍历数组时遍历的是数组的元素下标而非数组中的元素值
- enumerable properties:for...in 遍历的是可枚举属性。
- including inherited properties:for...in还会遍历继承来的属性。如需排除掉继承来的属性,需要用
hasOwnProperty()来做过滤。 - for...in 可以使用 break, return, throw语句中断遍历。
for...of
MDN介绍:
The for...of statement creates a loop iterating over iterable objects, including: built-in String, Array, array-like objects (e.g., arguments or NodeList), TypedArray, Map, Set, and user-defined iterables. It invokes a custom iteration hook with statements to be executed for the value of each distinct property of the object.
特点:
- iterable objects: for...of 遍历的是ES6引入的iterable对象,例如:字符串,数组,类数组的对象(arguments, NodeList等),TypedArray, Map, Set以及其他 iterable对象。
- for...of对于类数组的对象可以直接迭代,而无需
[].slice.call(),Array.from()这样的数组转化 - to be executed for the value of each distinct property of the object:for...of迭代的是对象属性的属性值而非属性名。并且不会迭代继承来的属性值。
- for...of 可以使用 break, return, throw语句中断迭代。
Array.prototype.forEach()
MDN 介绍:
Note: There is no way to stop or break a forEach() loop other than by throwing an exception. If you need such behavior, the forEach() method is the wrong tool.
Early termination may be accomplished with:
- A simple for loop
- A for...of / for...in loops
- Array.prototype.every()
- Array.prototype.some()
- Array.prototype.find()
- Array.prototype.findIndex() Array methods: every(), some(), find(), and findIndex() test the array elements with a predicate returning a truthy value to determine if further iteration is required.
-
forEach遍历数组的时候是无法通过 break或者return false中断遍历的, 只能通过抛异常来中断。
-
对于类数组的对象(例如:arguments),要想遍历其数值,无法直接使用数组的 forEach方法(因为他们只是看上去像数组但却不是数组的实例),但可以使用
for...of或者先使用[].slice.call或Array.from方法将类数组对象转换成数组然后再使用数组的forEach方法遍历数值例如: