Handwriting can deepen the understanding of map, sometimes understand but not necessarily write, I hope we can do more, don’t play so much talk! Be a giant of action!
Map can pass in a callback function that returns a value. The map using
var arr = [1.2.3.4]
var array = arr.map((item, index) = > {
return item * 2
})
console.log(array);
Copy the code
handwritten
var arr = [1.2.3.4];
function map(arr, mapCallback) {
// 1: Check whether the parameters are correct
if (!Array.isArray(arr) || ! arr.length ||typeofmapCallback ! = ='function') {
return[]}else {
// Do the following
let result = []
for (let i = 0, len = arr.length; i <= len; i++) {
result.push(mapCallback(arr[i], i, arr))
}
return result
}
}
var sb = map(arr, (item) = > {
return item * 2
})
console.log(sb);
Copy the code