简体   繁体   中英

Getting error Uncaught TypeError: Cannot read property 'toLowerCase' of undefined

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); 

Why OP's code donot work?

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.

  • Now consider then the array length is 1
  • then array.slice(1) will return []
  • an empty array will be passed to map() .
  • For an empty array array[0] will `undefined
  • then undefined will be passed to callback
  • undefined.toLowerCase throws error.

Conclusion

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM