Getting error Uncaught TypeError: Cannot read property 'toLowerCase' of undefined while executing this code.
const map = (array, callback) => {
return [callback(array[0])].concat(map(array.slice(1),callback));
}
var lower = map(['A','B','C'],function (val) {
return val.toLowerCase()
});
console.log(lower);
You need to check if array length
is 1
then only return the element because there are no other elements left.
const map = (array, callback) => { if(array.length === 1) return [callback(array[0])] return [callback(array[0])].concat(map(array.slice(1),callback)); } var lower = map(['A','B','C'],function (val) { return val.toLowerCase() }); console.log(lower);
It seems that you want to create your own map()
. In think you loop is better than recursion.
const map = (array, callback) => { let res = [] for(let i = 0;i<array.length;i++){ res[i] = callback(array[i],i) } return res; } var lower = map(['A','B','C'],function (val) { return val.toLowerCase() }); console.log(lower);
The code in question uses recursion. And whenever we use recursive approach we should have a condition to return the function with calling it again.
length
is 1
array.slice(1)
will return []
map()
. array[0]
will `undefined undefined
will be passed to callback
undefined.toLowerCase
throws error. You don't need to run the part .concat(map(array.slice(1),callback))
when only one element is left in array. Because there is noting more to concat()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.