Problems with Javascript arrays

Asked

Viewed 80 times

1

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

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

Uncaught Typeerror: Cannot read Property 'Trim' of Undefined(...)

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

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

Can someone give me a clue as to why this problem is happening?

  • 3

    How much is it worth i at the time of execution?

  • 1

    That code is running within a cycle for? I see a risk of i + 1 be greater than the index of the last element of the array and give undefined because of this. As @Emoon asked, what is the value of i and what is the value of lineOut.length when this error occurs?

  • @Emoon for(var i = 0; i<lineOut.length; i++) this is the header of my loop.

  • @Sergio i = 0 and lineOut.length = 2. But I’m probably overflowing the array index. I’m going to develop another logic to solve this problem. Thank you very much for the comment.

1 answer

1


Your code must look something 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, the i vale (total - 1) and the array lineOut goes from lineOut[0], lineOut[1], ..., lineOut[total - 1]. You’re trying to catch lineOut[i + 1], which is equal to lineOut[(total - 1) + 1], that is to say, lineOut[total], that is out of bounds (only goes up lineOut[total - 1]).

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

  • 1

    @Michele Akemi really that’s right, I’ll add a condition pro undefined. Thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.