我是靠谱客的博主 秀丽毛豆,这篇文章主要介绍简单手写forEach等6个循环函数1.forEach2.map3.filter4.every5.some6.find7.findIndex,现在分享给大家,希望可以做个参考。
1.forEach
复制代码
1
2
3
4
5Array.prototype.newForEach = function (callback) { for (let i = 0; i < this.length; i++) { callback(this[i], i, this) } }
问:为什么return不能跳出整个循环
答:return可以跳出当前callback,, 而不能跳出整个for循环,类似for里面的continue
复制代码
1
2
3
4
5
6
7
8let arr = ['杰', '杰你', '哥们'] arr.newForEach(item => { if (item == '杰你') { return } console.log(item); })
问:那怎么跳出整个循环?
答:try catch
复制代码
1
2
3
4
5
6
7
8
9
10
11let arr = ['杰', '杰你', '哥们'] try { arr.newForEach(item => { if (item == '杰你') { throw '错误' } console.log(item); }) } catch (error) { console.log(error); }
2.map
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14let arr = [{ name: '小白', age: 19 }, { name: '小宏', age: 17 }] Array.prototype.newMap = function (callback) { // 返回一个处理后的数组 let res = [] for (let i = 0; i < this.length; i++) { res.push(callback(this[i], i, this)) } return res } let newArr = arr.newMap(item => { //返回处理的内容 return `${item.name}今年${item.age}` }) console.log(newArr);
3.filter
复制代码
1
2
3
4
5
6
7
8
9
10
11
12Array.prototype.newFilter = function (callback) { let res = [] for (let i = 0; i < this.length; i++) { callback(this[i], i, this) && res.push(this[i]) } return res } let arr = [1, 2, 3, 4, 5] let newArr = arr.newFilter(item => { return item > 3 }) console.log(newArr);
4.every
复制代码
1
2
3
4
5
6
7
8
9
10
11
12Array.prototype.newEvery = function (callback) { for (let i = 0; i < this.length; i++) { //循环,如果有一个false就返回false if (!callback(this[i], i, this)) return false return true } } let arr = [1, 2, 3, 4, 5] let res = arr.newEvery(item => { return item > 0 }) console.log(res);
5.some
复制代码
1
2
3
4
5
6
7
8
9
10
11Array.prototype.newSome = function (callback) { for (let i = 0; i < this.length; i++) { if (callback(this[i], i, this)) return true } return false } let arr = [1, 2, 3, 4, 5] let res = arr.newSome(item => { return item > 14 }) console.log(res);
6.find
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13Array.prototype.newFInd = function (callback) { for (let i = 0; i < this.length; i++) { if (callback(this[i], i, this)) { return this[i] } } return '未找到'//原版是undefined } let arr = [{ id: 1, name: "小编" }, { id: 2, name: "小百" }] let res = arr.newFInd(item => { return item.id == 21 }) console.log(res);
7.findIndex
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13Array.prototype.newFindIndex = function (callback) { for (let i = 0; i < this.length; i++) { if (callback(this[i], i, this)) { return i //如果找到返回当前索引 } } return '找不到索引'//原版是-1 } let arr = [{ id: 11, name: "小编" }, { id: 2, name: "小百" }] let res = arr.newFindIndex(item => { return item.id == 2 }) console.log(res);
最后
以上就是秀丽毛豆最近收集整理的关于简单手写forEach等6个循环函数1.forEach2.map3.filter4.every5.some6.find7.findIndex的全部内容,更多相关简单手写forEach等6个循环函数1内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复