JS中forEach方法的使用
JS中forEach方法的使用
·
一:概念
forEach()
方法按升序为数组中含有效值的每一项执行一次callback
函数,那些已删除或者未初始化的项将被跳过(例如在稀疏数组上)。
注意:
forEach()
的返回值为undefined
forEach()
对于空数组是不会执行回调函数的- 没有办法中止或者跳出
forEach()
循环,除了抛出一个异常
二:语法
arr.forEach(callback(currentValue, index, arr), thisArg)
arr.forEach((item, index, arr) => {})
参数说明:
callback
:必须。为数组中每个元素执行的函数,该函数接受三个参数:
currentValue
:必须。数组中正在处理的当前元素。index
:可选。当前元素的索引值。arr
:可选。方法正在操作的数组。
thisArg
:可选。当执行回调函数时用作this
的值(参考对象)。
三:实例
将这个数组中id值提取出来重新组成一个新数组
var arr = [{
id: 1,
name: '张一',
age: 25,
class: '一班'
}, {
id: 1,
name: '张二',
age: 25,
class: '二班'
}, {
id: 2,
name: '张三',
age: 25,
class: '三班'
}]
let newArr1 = [];
arr.forEach((item, index, arr) => {
console.log(item, item.id, index, arr);
newArr1.push(item.id)
})
console.log(newArr1);
打印的结果如下图所示:
更多推荐
已为社区贡献2条内容
所有评论(0)