每日一篇,JS-API 第一篇 "forEach"

294 阅读2分钟

1.前言

通过MDN文档对Object、String、Array等进行记录学习

2.Array_forEach_2021-03-30

Array.propotype.forEach()

// 案例
var arr = ['vue', 'react', 'angular']
list.forEach(function(item, index, arrry){
    console.log(item, index, arrry)
})

// 语法
arr.forEach(callback(currentValue [, index [, array]]) [,thisArg])

// 参数
callback
    为数组中每个元素执行的函数、改函数接受三个参数:
    
    currentValue
        数组中正在处理的当前元素
    
    index 可选
        数组中正在处理的当前元素的索引
        
    array 可选
        forEach() 方法正在操作的数组

thisArg 可选
    可选参数、当执行回调callback函数时、作用this的值

// 返回值
undefined

forEach 重写

forEachArray数组prototype原型上的方法 但是一直也没有想过要去重写 这里我们写一个属于自己的myForEach方法

// 当前这个是案例
var arr = ['vue', 'react', 'angular']
list.forEach(function(item, index, arrry){
    console.log(item, index, arrry)
})


/**  
 * @author 栾树
 * @date 2021-04-01
 * @description { forEach } 重写
 * @param {Function} callback 
 */

Array.prototype.myForEach = function (callback) {
  // 理一下思路 
  // 1. 首先我们在调用forEach的时候传入了一个方法 

  // 2.文章上面讲过 forEach 有着属于自己的第二个参数

  // 3.那我知道当前要循环几次呢? 这里先买个关子 哈哈

  // 4.当前方法中的this指向是指向的谁呢

  // 5.forEach方法第二次参数如果不传 那么在输出this的时候会指向谁呢


  // 首先我们经常听到一句话 就是谁调用 那么this就是谁 那么这里的this指向不就是 arr.forEach 那么this指向就是arr那个调用的本身
  var _arr = this,
    // 当前是数组 本来也是数组原型的方法 准备操作数据的 所以这里可以提前缓存arr的长度 提升for循环的性能
    _len = this.length,
    // 其实我们经常忽视了arguments的使用  这里如果有传入第二个值我就接受 没有我就赋值window
    _arg2 = arguments[1] || window;

  // 好了 重写正式开始
  for(var i =0; i< _len; i++){
    // 通过apply绑定this的指向问题  这里后期我会出一篇文章专门讲解 apply call 针对this指向的问题
    callback.apply(_arg2, [_arr2[i], i, _arr]);
  }

}

// 测试我们的myForEach
var a = {
    name:'栾树'
}

list.myForEach(function(item, index, arrry){
    console.log(this); // 传入第二个参数的话 this就是传入的这个参数 没有传入的话就是window
    console.log(item, index, arrry)
},a)

系列文章