map()

作者: 我食四条鱼 | 来源:发表于2017-12-04 21:46 被阅读0次

    遍历数组的每一项元素,并且在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);
    

    相关文章

      网友评论

          本文标题:map()

          本文链接:https://www.haomeiwen.com/subject/yyufixtx.html