Javascript数组长度属性
我正在通过名为learnyounode。 #9是“JUGGLING ASYNC”,说明是以3个URL作为参数,并按参数顺序输出内容。 我通过包括一个柜台来解决问题,但是我原来的工作没有成功:
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); }); } })); }); } });
现在的东西工作正常,如果你用第12行的计数replacestore.length,我只是不明白为什么数组的长度是不够的。 有人知道吗?
在javascript数组中,当你给一个空数组的索引为5的项时,这意味着这个数组的长度是6个,项0-4是未定义的。
例如
var x = []; console.log(x.length); //prints 0; x[2] = "hello, world"; console.log(x.length); //prints 3;
你跳过前两个元素,但仍然使用index
,所以当你input你的第一个元素到store
,你input到store[2]
,长度为3,当count
只有1。
你应该使用你的count
variables,因为:
当你store[1] = data.toString();
,例如,你得到一个长度为2的数组[undefined, 1]
,你希望它是1。