js-array-map方法使用
map()方法创建一个新数组,其结果是该数组中的每个元素是调用一次提供的函数后的返回值。
let newArray = [1,2,3,4,5,65,'a','cc'];
newArray.map((item, index)=>{
console.log(item, index);
});
使用变量接收回传数组
let targetArray = newArray.map((item,index)=>{return item});
console.log(targetArray);
重写一个类似map的方法anotherMap
实现map的部分功能
实现map的遍历数组项功能,并且以数组的形式回传。
Array.prototype.anotherMap = function (callback) {
let targetArray = Object(this);
let len = targetArray.length;
let i = 0;
let receiveArr = new Array(len);
while (i < len) {
let mappedValue;
if (i in targetArray) {
mappedValue = callback(targetArray[i], i);
}
receiveArr[i] = mappedValue;
i++;
}
return receiveArr;
};
newArray.anotherMap((item, index) => {
console.log(item, index);
});
let targetArray2 = newArray.anotherMap((item) => item * 10);
console.log(targetArray2);