for和forEach的区别
- for循环可以使用break和continue终止、跳出循环,但forEach不能,可以使用try catch抛出异常;
- for循环可以控制循环的起点,forEach只能默认从索引0开始;
- for循环过程中支持修改索引,但forEach不能(底层控制索引自增);
forEach参数
复制代码
1
2arr.forEach(function(self,index,arr){},this)
self:数组当前遍历的元素,默认从左往右依次获取数组元素
index:数组当前元素的索引,第一个元素索引为0,依次类推
arr:当前遍历的数组
this:回调函数中this指向
复制代码
1
2
3
4
5
6
7
8
9
10const arr1 = [1, 2, 3, 4]; const obj = { a: 1 } arr1.forEach(function (self, index, arr) { console.log(`当前元素为${self}索引为${index},属于数组${arr}`) //做个简单计算 console.log(self + this.a) }, obj)
arr:参数其实就是正在遍历的数组arr1
this:指向的是obj
数组去重
复制代码
1
2
3
4
5
6
7
8let arr1 = [1, 2, 1, 3, 1] let arr2 = [] arr1.forEach(function (self, index, arr) { // arr就是arr1 arr.indexOf(self) === index ? arr2.push(self) : null }); console.log(arr2) // [1,2,3]
es6数组去重
复制代码
1
2
3
4let arr1 = [1, 2, 1, 3, 1] console.log([...new Set(arr1)]) // [1,2,3]
最后
以上就是紧张电脑最近收集整理的关于for和forEach的区别的全部内容,更多相关for和forEach内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复