forEach(function) 用于调用数组的每个元素,并将元素传递给回调函数。原数组不变。对数组的每个元素执行一次提供的函数。没有返回值
注意点:
1. 如果只有一个参数,那么就是 数组内容
2. 它的语句结构里面不支持break、continue和return语句 ,break和continue会直接报错,不会读取return语句
语法:
复制代码
1
2
3
4
5
6
7
8
9
10
11let array = ['a', 'b', 'c'] array.forEach(function(element) { console.log(element) 输出 a b c }) 或 array.forEach((a)=> { console.log(a); 输出 a b c })
属性:
foreach方法主要有三个参数,分别是数组内容、数组索引、整个数组
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19let arr = ['a', 'b', 'c'] // 数组内容、数组索引、数组本身 arr.forEach(function (value, index, array) { console.log(value) console.log(index) console.log(array) }) 输出: a // 数据内容 0 // 索引 ['a', 'b', 'c'] // 数组本身 b 1 ['a', 'b', 'c'] c 2 ['a', 'b', 'c']
对比:
forEach() 方法对数组的每个元素执行一次提供的函数。总是返回undefined;
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14let arr = [1,2,3,4]; arr.forEach(alert); // 等价于: let arr = [1, 2, 3, 4]; for (let k = 0, length = arr.length; k < length; k++) { alert(array[k]); }
forEach和map的区别:
区别主要在于map有返回值,而forEach没有返回值
forEach:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15let arr = [0,2,4,6,8]; var newArr = arr.forEach(item=>{ console.log(item) return item/2; },this); console.log(newArr); // 输出 0 2 4 6 8 undefined
map:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15let arr = [0,2,4,6,8]; let newArr = arr.map(item=>{ console.log(item) return item/2; },this); console.log(newArr); // 输出 0 2 4 6 8 [0,1,2,3,4]
最后
以上就是幽默薯片最近收集整理的关于【JavaScript】- forEach的用法语法:属性: 对比:forEach和map的区别:的全部内容,更多相关【JavaScript】-内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复