forEach 的功能:用来遍历数组的方法
一、思路
通过实例化构造函数创建对象,设置对象的属性和方法,添加forEach函数,让形参为回调函数,在遍历原数组的时候,执行回调函数,获取相应的值。
知识点:
- new关键字做了什么事
- this 的指向问题
- 形参和实参的区分
- 参数列表arguments如何转换为数组
二、实现步骤
(一) 实现基础需求, 接受回调函数,包含三个参数(当前元素,索引和数组本身)
核心: this 的指向,怎么实现回调函数执行时获得数组的元素,索引,和 数组?
怎么调用的?
this指向: 回调函数没有明显调用主题,this指向 window 对象;
回调函数执行时获得数组的元素: 遍历时获取相应的值,作为实参传递
- 代码如下:
function callbackEach(currentValue, index , arr){
console.log(this ,'callbackEach') // 回调函数没有明显调用主体, this = window
console.log(currentValue, index, arr)
}
function Brray(arr){
this.arr = arr
this.forEach = function (callbackEach, obj) {
for(var i = 0, len = this.arr.length; i < len; i++){
callbackEach(this.arr[i], i, this.arr)
}
}
}
var arr = new Brray([4,6,8,10,12])
arr.forEach(callbackEach)
- 运行截图
(二) 修改参数的个数,可以有两个参数,并且第二个参数为回调函数this将要指向的对象
核心: 回调函数执行时,this 默认指向window对象,怎么修改为自己想要的对象?
可以参考以为博主的文章: js 改变this 的三种方法https://blog.csdn.net/hongchen_lian/article/details/103920074
- 代码如下:
function callbackEach(currentValue, index , arr){
// 回调函数执行,this 指向window对象
console.log(this, 'callbackEach')
console.log(currentValue, index, arr)
this.value = currentValue
this.index = index
this.arr = arr
}
function Brray(arr){
this.arr = arr
this.forEach = function (callbackEach, obj) {
// this 在对象调用时,指向当前数组对象
// 1. 遍历数组对象的每一个元素,执行回调函数
for(var i = 0, len = this.arr.length; i < len; i++){
callbackEach.call(obj,this.arr[i], i, this.arr)
}
}
}
var arr = new Brray([4,6,8,10,12])
var obj = {
name: '大BOSS'}
arr.forEach(callbackEach, obj)
- 运行截图如下
(三)修改参数为可变的,其中包含: forEach的参数是可变的,回调函数的参数也是可变的
核心: 通过什么方式可以接受不定参数?
可以参考一个博主的文章js实现可变参数https://www.php.cn/js-tutorial-494640.html
- 代码如下
function callbackEach(currentValue){
var args = [].slice.call(arguments) // 将arguments 转为数组
var currentValue = args[0], index = args[1], arr = args[2] // 第一个参数是 当前值,第二个参数是 索引, 第三个参数是 数组
console.log(this , '回调函数') // 回调函数如果没有明显调用主体, this = window
if (args.length === 3){
console.log(currentValue, index, arr)
}
if(args.length === 2){
console.log(currentValue, index)
} if (args.length === 1){
console.log(currentValue)
}
// 通过判断数组的长度让不同的参数列表有不同的输出
}
function Brray(arr){
this.arr = arr
this.forEach = function (callbackEach) {
if(arguments[1]) {
for(var i = 0, len = this.arr.length; i < len; i++){
callbackEach.call(arguments[1],this.arr[i], i)
}
} else {
for(var i = 0, len = this.arr.length; i < len; i++){
callbackEach(this.arr[i], i ,this.arr) // 控制实参的个数,人工控制住
}
}
}
}
/* ========使用=============*/
var obj = {
name: '大BOSS'
}
var arr = new Brray([4,6,8,10,12])
arr.forEach(callbackEach)
- 运行截图
forEach 接受两个参数,回调函数和 新的Object对象
回调函数接受两个参数: 当前值和索引
forEach 接受一个参数: 回调函数
但是回调函数传参为一个 数,就会声明一个数组,回调函数传参有3个值
总结: 任何一个方法都是经过练习才会掌握的,第一次先尝试实现基础的,原始的功能,但是切记做完后回头看,思考+实践 才会更上一层楼。
callbackEach.call(obj,this.arr[i], i, this.arr),将函数参数列表的值转换为json,传递参数
callbackEach.call(obj,this.arr[i], i, this.arr),将函数参数列表的值转换为json,传递参数
暂时先到这里结束啦, 有什么问题或者建议都评论或者私信提醒下我嘛,要一起进步的呀~~~