Home > Software design >  Undefined properties in array split
Undefined properties in array split

Time:08-11

So, I have this here function designed to split the array elements and return them to two separate arrays. Problem is, when I try yo run it it returns "Challenges.js:32 Uncaught TypeError: Cannot read properties of undefined (reading 'split')" I don't really get it, what am I missing here? Sorry for the noob question, been studying for less than two weeks :D

const array0 = [
    "3:1",
    ...
    "4:0",
  ];
let array1 = [];
let array2 = [];

for (let i = 0; i <= array0.length; i  ) {
    array1.push(array0[i].split(":")[0]);
    array2.push(array0[i].split(":")[1]);
  }
  
  console.log(array1, array2);

CodePudding user response:

The condition of for loop should be i < array0.length instead of i <= array0.length

CodePudding user response:

your for loop is wrong, it should be

for (let i = 0; i < array0.length; i  ) {

}

and not

for (let i = 0; i <= array0.length; i  ) {

}

CodePudding user response:

You need to change that <= to < or add -1 after array0.length:

for (let i = 0; i < array0.length; i  ) {
    array1.push(array0[i].split(":")[0]);
    array2.push(array0[i].split(":")[1]);
  }

both ok

for (let i = 0; i < array0.length -1; i  ) {
    array1.push(array0[i].split(":")[0]);
    array2.push(array0[i].split(":")[1]);
  }
  • Related