Array.prototype.map()

Array.prototype.map()

遍历加工,不改变原数组,与foreach相似,但优于foreach

  • 模仿foreach的用法
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
words.map(item => {
    console.log(item);
});
  • 一般用法
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
let a = words.map(item => {
    return 1
});
console.log(a);  //[ 1, 1, 1, 1, 1, 1 ]
  • 手动实现(必须要掌握,不要让它成为曾经会写的东西)
Array.prototype.map = function(callback, thisArg) {
    if(typeof callback != 'function') throw new TypeError(callback + 'must be a function')
    let arr = this
    let thisValue = arguments[1] || this
    let returnValue = []
    for(let i = 0; i < arr.length; ++i) {
        if(callback.call(thisValue, arr[i], i, arr)){
            let result = callback.call(thisValue, arr[i], i, arr)
            returnValue.push(result)
        }
    }
    return returnValue
};
let a = [1,2,3].map(item => {
    // console.log(item);
    return 1
})
console.log(a);  //[ 1, 1, 1 ]
/*
* 把console.log放开之后会输出两行一样的,是因为当进入if循环之后,它又能调用一下callback方法,而这个callback就是你外面map里面传的函数,所以又输出了一遍,而先前if判断里面也调用了一遍callback方法,所以加起来两遍
* 因为你在外面的map那里返回了一个1,所以callback.call()是有返回值的,所以能进入if判断,因为callback.call()本质上就是callback()的调用,也就是你在外面那个map里面传的函数
* */
posted @ 2022-06-13 18:55  朱在春  阅读(38)  评论(0编辑  收藏  举报