Matt Murphy
Matt Murphy

Reputation: 330

Javascript array.length property

I'm working through the fabously-named learnyounode. #9 is "JUGGLING ASYNC" and the instructions are to take in 3 urls as params and output the content in parameter order. I got it working by including a counter, but my original did not work:

var http = require('http'),
  bl = require('bl'),
  store = [],
  count = 0; //added later

process.argv.forEach(function(element, index, array) {
  if (index > 1) {
    http.get(element, function(response) {
      response.pipe(bl(function(err, data) {
        store[index] = data.toString();
        count++; //added later
        if (store.length == 3) {
            store.forEach(function(e,is,a) {
                console.log(e);
            });
        }
      }));
    });
  }
});

Now the thing works fine if you replace store.length with count on line 12, I just can't figure out why .length on the array wasn't enough. Anyone know?

Upvotes: 1

Views: 1698

Answers (2)

Seva Arkhangelskiy
Seva Arkhangelskiy

Reputation: 685

You should use your count variable, because:

When you you do store[1] = data.toString();, for example, you get an array [undefined, 1] with length = 2. And you want it to be 1.

Upvotes: 0

redbmk
redbmk

Reputation: 4796

In javascript arrays, when you give an empty array an item at index 5, it implies that the array is 6 items long, with items 0-4 being undefined.

For example

var x = [];
console.log(x.length); //prints 0;
x[2] = "hello, world";
console.log(x.length); //prints 3;

You're skipping the first two elements but still using index, so when you enter your first element into store, you're entering it into store[2], making the length 3, when count is only 1.

Upvotes: 4

Related Questions