编写时间:2019-08-15
更新时间:2019-08-15 12:10作者:鬼小妞
目录:
备注: 本文
总结了forEach()参数中callback的参数状态:
更新完毕2019-08-15
- myArr.forEach(callback(currentValue, index, array), thisArg)
- myMap.forEach(callback(value, key, Map), thisArg)
- mySet.forEach(callback(currentValue, currentKey, Set), thisArg)
数组 Array.prototype.forEach()
arr.forEach(callback(currentValue, index, array), thisArg);
- callback
为数组中每个元素执行的函数,该函数接收三个参数:
- currentValue - 数组中正在处理的当前元素。
- index - 可选 数组中正在处理的当前元素的索引。
- array - 可选 forEach() 方法正在操作的数组。
- thisArg可选 可选参数。当执行回调函数时用作 this 的值(参考对象)。
map映射 的 Map.prototype.forEach()
myMap.forEach(callback(value, key, Map), thisArg)
-
callback 函数有三个参数:
- value - 元素的值
- key - 可选元素的键
- map - 可选当前正在被遍历的对象
-
thisArg可选。当执行回调函数时用作 this 的值(参考对象)。
Set的 Set.prototype.forEach()
mySet.forEach(callback(currentValue, currentKey, Set), thisArg)
forEach 方法会依次为集合中的元素执行回调函数,就算元素的值是 undefined 。 回调函数有三个参数:
- callback 函数有三个参数:
- currentValue - 元素的值
- currentKey - 可选 元素的索引
- set - 可选 正在遍历的集合对象
- thisArg可选。当执行回调函数时用作 this 的值(参考对象)。
currentValue 是正在被操作的元素。并且由于集合没有索引,所以 currentKey 也表示这个正在被操作的元素。
但是由于集合对象中没有索引(keys),所以前两个参数都是Set中元素的值(values),之所以这样设计回调函数是为了和Map 以及Array的 forEach 函数用法保持一致。
节点列表 NodeList.prototype.forEach()
myNodeList.forEach(callback(currentValue, currentIndex, listObj), thisArg)
-
callback 函数有三个参数:
-
currentValue - 正在节点列表中处理的当前元素值。
-
currentIndex - 正在节点列表中处理的当前元素的索引。
-
listObj - 正在应用forEach()的NodeList对象。
-
-
thisArg可选。当执行回调函数时用作 this 的值(参考对象)。
对象forEach
对象的forEach()遍历其实还是把key或value转换为数组之后,利用数组的forEach遍历
Object.keys(myObject).forEach()