Problems with Javascript arrays

1

Well, I'm having some problems with the following code snippet:

alert(lineOut[i].trim() + " - - " + lineOut[i + 1].trim());
  

Uncaught TypeError: Can not read property 'trim' of undefined (...)

The array lineOut is a dynamically populated array, which at the time of execution of the above excerpt has the following values:

lineOut = ["6", "Comentario"];

Can anyone give me a glimpse of why this problem is happening?

    
asked by anonymous 14.11.2016 / 23:02

1 answer

1

Your code should look like this:

var total = lineOut.length;
for (var i = 0; i < total; i++) {
    alert(lineOut[i].trim() + " - - " + lineOut[i + 1].trim());
}

The problem is that in the last iteration, i is (total - 1) and the lineOut array goes from lineOut[0], lineOut[1], ..., lineOut[total - 1] . You are trying to get lineOut[i + 1] , which is equal to lineOut[(total - 1) + 1] , that is, lineOut[total] , which is out of bounds (only goes to lineOut[total - 1] ).

When you try to access something outside the bounds of an array, JS returns undefined .

    
15.11.2016 / 01:14