Skip to content
Advertisement

Cannot Read Property “toString” of Undefined – Javascript [closed]

I am attempting to take an array of numbers, convert them to strings (and then a single string) so that I can easily store multiple values in a key:value db (5 2 digit numbers -> one 10 digit number). I have an array of 5 numbers, a function with a for loop inside that I want to look at array[i], pull out the number, and convert it to a string.

var index1 = [0, 4, 6, 2, 11]

// merge indexes into one number - to be stored in db - take apart when called
function storeVal() {
  let valueArray = []
  for(i = 0; i <= index1.length; i++) {
    let num = index1[i].toString()
    if  (num.length < 2) {
      let newString = '0' + num
      valueArray.push(newString)
    } else {
      valueArray.push(num)
    }
  }
  return valueArray
}
console.log(storeVal())

This code gave me an error “Cannot Read Property “toString” of Undefined “. When I change the index1[i] line it doesn’t throw the error, but doesn’t allow me to use the right values.

Advertisement

Answer

I think the issue is you are running the loop till it is less than or equal to the size of array index1.

To fix this, you can change the part of the for loop

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

to

for(i = 0; i < index1.length; i++) {
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement