简体   繁体   中英

how can i fix this: Uncaught TypeError: Cannot read property 'toString' of undefined in javascript

trying to write a function that takes a string, and returns the string back with first letter of each word in capital. i am able to do so. But i keep on getting undefined value at my first index value in the iteration, tho the i have items in my list.

i wrote my function that takes a string parameter. i pass my parameter in to split using split(" ") method it so i can get an array of words. and when i created my forloop to go over all of them to be able to make each of their first letters Capital. now in the iteration, i create a variable to store the first index element converted into a string using the toString() method so i can later apply the toUpperCase() method on it

When i do a console.log() in the for loop i can see the elements converted all listed out (when i execute the function and pass a string to it)

But i do not understand why i get: Uncaught TypeError: Cannot read property 'toString' of undefined...and this error points to the variable holding the element at index [i] when i am converting it to string in the forloop: var pickString = newStringList[i].toString()

function capitalizeLertters (letter) {
    var newStringList = letter.split(" ");
    // console.log(newStringList[0])
    var addAll = []

    for (var i = 0; i <= newStringList.length; i++) {
        console.log(newStringList[i])
        var pickString = newStringList[i].toString()
        // console.log(pickString)
        var finalString = pickString.charAt(0).toUpperCase() + pickString.slice(1)
        // console.log(finalString)
    }
    addAll.push(finalString)
    // console.log(addAll)
    return addAll
}

console.log(capitalizeLertters("js string exercises"))

This is my expected result: "Js String Exercises"

And these are the different console.log results

""js Js string String exercises Exercises""

But my function does not execute in the end...it throws this:

"""learnJs.js:100 Uncaught TypeError: Cannot read property 'toString' of undefined at capitalizeLertters (learnJs.js:100) at learnJs.js:110"""

So

  1. You don't need toString() on a String

  2. The for loop crashes at the last element because you should stop at length -1 or simply replace <= with < .

  3. You are calling addAll after the loop, so it only adds the last element.

  4. You are returning an array and I assume you want the String, so you can use join() on the array.

 function capitalizeLertters (letter) { var newStringList = letter.split(" "); var addAll = []; for (var i = 0; i < newStringList.length; i++) { var pickString = newStringList[i]; var finalString = pickString.charAt(0).toUpperCase() + pickString.slice(1); addAll.push(finalString); } return addAll.join(" "); } console.log(capitalizeLertters("js string exercises")) 

please check the modifications

  • push() method should be inside the loop.
  • you are looping from index 0, thats why you need to use < instead of <=
  • finally need to use join method to get string from array

Solution :

function capitalizeLertters (letter) {
    var newStringList = letter.split(" ");
    // console.log(newStringList[0])
    var addAll = [];

    for (var i = 0; i < newStringList.length; i++) {
        console.log(newStringList[i]);
        var pickString = newStringList[i];
        // console.log(pickString)
        var finalString = pickString.charAt(0).toUpperCase() + pickString.slice(1);
        // console.log(finalString)
        addAll.push(finalString);
    }
    // console.log(addAll)
    return addAll.join(" ");
}

capitalizeLertters("js string exercises");

An array starts with the index number 0. The length of newStringList is 3. If you give a less than (<) then 'i' will go like 0("js"), 1("string"), 2("exercises"). If you give a less than equal (<=) it will go like 0("js"), 1("string"), 2("exercises"), 3(undefined).

  function capitalizeLertters (letter) {
  var newStringList = letter.split(" ");

  var addAll = ""

  for (var i = 0; i < newStringList.length; i++) {

  var pickString = newStringList[i].toString()

  var finalString = pickString.charAt(0).toUpperCase() + pickString.slice(1)
  addAll += finalString
  if(i != newStringList.length-1){
    addAll +=" "
  }
}


return addAll
}

console.log(capitalizeLertters("js string exercises"))

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