forEach:无返回值,单纯的遍历数组

  1. Array.prototype.myForEach = function (callback) {//在数组的原型上添加myForEach方法,接收一个回调函数
  2. for (let i = 0; i < this.length; i++) {
  3. let item = this[i];//定义回调函数接收的三个参数
  4. let index = i;
  5. let array = this;
  6. callback(item, index, array)//调用回调函数
  7. }
  8. }
  9. const arr = [{
  10. id: 0,
  11. name: "我"
  12. },
  13. {
  14. id: 1,
  15. name: "是"
  16. }
  17. ]
  18. arr.myForEach((item, index) => {
  19. console.log(item);
  20. })

map: 创建一个新数组,其结果是该数组中的每个元素都调用一个提供的函数后返回的结果

  1. /**
  2. * @param {callback} 回调函数
  3. * @param {thisArg} 执行 callback 函数时值被用作this。
  4. */
  5. Array.prototype.myMap = function(callback,thisArg){
  6. // 处理数组类型异常
  7. if (this === null || this === undefined) {
  8. throw new TypeError("Cannot read property 'map' of null or undefined");
  9. }
  10. // 处理回调类型异常
  11. if (Object.prototype.toString.call(callback) != "[object Function]") {
  12. throw new TypeError(callback + ' is not a function')
  13. }
  14. let T = thisArg
  15. console.log(T);
  16. let A = new Array(this.length)
  17. for(let i = 0;i < this.length; i++){
  18. //依次传入this, 当前项,当前索引
  19. A[i] =callback.call(T,this[i],i)
  20. }
  21. return A
  22. }
  23. //callback == function(item,index){return item*item}
  24. let arr = [1,3,5,7,8,9]
  25. let res = arr.myMap((item,index) => {
  26. return item*item
  27. })
  28. console.log(res)

reduce

  1. /**
  2. * @param {callback}
  3. * ruducer(callback)接受四个参数 accumulator currentValue index array
  4. * accumulator 表示累计器累计回调的返回值; 它是上一次调用回调时返回的累积值,或initialValue
  5. * currentValue 当前值
  6. * index 当前索引
  7. * array 调用reduce的数组
  8. * @param {initialValue}
  9. * 作为第一次调用 callback函数时的第一个参数的值。如果没有提供初始值,则将使用数组中的第一个元素。 在没有初始值的空数组上调用 reduce 将报错。
  10. */
  11. //核心点 处理initialValue 返回值
  12. Array.prototype.myReduce = function(callback,initialValue){
  13. if(this === null || this === undefined){
  14. throw new Error("Cannot read property 'myReduce' of null or undefined")
  15. }
  16. if(Object.prototype.toString.call(callback) != "[object Function]"){
  17. throw new Error(`${callback} is not a function`)
  18. }
  19. let arr = Array.prototype.slice.call(this);
  20. let res = initialValue ? initialValue : arr[0]
  21. if(res === undefined){
  22. throw new Error('Each element of the array is empty');
  23. }
  24. let startIndex = initialValue ? 0 : 1 //如果没有提供initialValue reduce从索引1开始执行callback,提供initialValue从0开始
  25. for(let i = startIndex; i < arr.length; i++){
  26. res = callback.call(null,res,arr[i],i,this)
  27. }
  28. return res
  29. }
  30. let arr = [1,3,5]
  31. let r = arr.myReduce((accumulator,currentValue) => {
  32. return accumulator * currentValue
  33. },0) //16
  34. console.log(r);