-3

I have a problem here. You see, I have a JSON like:

enter image description here

All the elements are equals.

The thing is, when I execute this code:

var arrayProcesos = data['arrayProcesos'];
for(var k=0, len = arrayProcesos.length; k < len; k++) { //... }

The for iterates over the array (6 positions) and then goes to the position 6 (yes, the "7th element", I don't know why because it doesn't exist), and there it returns undefined.

Do you know how it can be possible and how to fix it?

EDIT:

Here is the code that returns the "undefined" error:

var proceso = arrayProcesos[k];
var nombreProceso = proceso['procesos']['denominacion'];

When it try to take ['procesos'], the Console says "Uncaught TypeError: Cannot read property 'procesos' of undefined"

Julian Ezequiel
  • 183
  • 1
  • 10
  • There is nothing wrong with the code which you posted. Can you post code within for loop? – Satpal Jul 29 '15 at 15:10
  • 1
    Based on the code you provided, it could go out of bounds if `len` is changed somewhere in the body. – pushkin Jul 29 '15 at 15:14
  • If i set up data as `var data = { arrayProcesos: [ "zero", "one", "two", "three", "four", "five" ] }` then this works fine as the body of the for: `console.log(k, arrayProcesos[k])` – Kenney Jul 29 '15 at 15:14
  • Why do you think it goes to position 6? What does your loop do? Can you please `console.log(k, len)` after the loop? This sounds like a duplicate of [console.log always appends a line saying undefined](http://stackoverflow.com/q/14633968/1048572) currently – Bergi Jul 29 '15 at 15:16
  • Try printing `k` like @Kenney is doing. – pushkin Jul 29 '15 at 15:16
  • 1
    Oh, is the code in your edit executing in the body of the for loop or outside of it? – pushkin Jul 29 '15 at 15:18
  • Yes Pushkin. Finally, I found that the var "len" was being used inside the loop (yep, copy-paste) so it modifies its value. Thank you all! – Julian Ezequiel Jul 29 '15 at 15:20
  • 1
    @JulianEzequiel Great to hear. Unless you expect the length of the array to change in the loop, I would recommend initializing `len` outside of the loop. Or just call `.length` directly in the stop condition. – pushkin Jul 29 '15 at 15:21

1 Answers1

1

I posted the solution as a comment, but to "close" up the question, I'll post it here.

The problem is that the len variable is being changed in the body of the for loop, which causes it to go out of bounds.

pushkin
  • 9,575
  • 15
  • 51
  • 95