map()

遍历数组的每一项元素,并且在map的第一个参数(回调函数)
中进行运算处理后返回计算结果。返回一个由所有计算结果组成的新数组。

const newArr = [1, 2, 3, 4].map(add, {a: 1});

function add(item, i, arr) {//item表示数组的值,i表示索引
    console.log(item, i, arr, this);
    return item + 1;
}

console.log(newArr);
  • 封装一个map()
Array.prototype._map = function (fn, context) {
    let tmp = [];
    if (typeof fn === 'function') {

        for (let i = 0; i < this.length; i++) {//封装for循环
            tmp.push(fn.call(context, this[i], i, this));
        }
    } else {
        console.error('TypeError:' + fn + 'is not a function');
    }
    return tmp;
};

const newArr = [1, 2, 3, 4]._map(fn);

function fn(item) {
    return item + 1;
}

console.log(newArr);
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。