'Cannot read property 'length' of undefined. Also trim and strip is not a function

There is code:

function Hours(days){
  weekHours = 0;
  for(i = 0; i != days.length; i++){
    if(days[i].length > 3){
      dayHours = days[i].trim().split('-');
      weekHours += parseFloat(dayHours[1]) - parseFloat(dayHours[0]);
    }
  }
  return weekHours;
}

var fruits = [" 8-16  ",    " 8-23 ",   " 17-23 ",  " 16-23 ",  " 8-16 ", " 12-18 ",    " В "];

console.log(Hours(fruits));

Why i have this errors:

TypeError: Cannot read property 'length' of undefined

TypeError: days[i].trim is not a function

TypeError: days[i].strip is not a function



Solution 1:[1]

It's acting as if an undefined or null is in your fruits array. Did you have an extra comma in it originally, because the code works fine as-is.

Meaning,

var fruits = ['8-16',' B ']; is fine but

var fruits = ['8-16',,' B ']; is not.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1