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