2016-09-17 65 views
0

我在这里很愚蠢吗? (我来自Ruby,所以可能有一些关于Javascript数组的东西,我错过了)。JavaScript数组与计算机不一致?

console.log(new_devices)

结果在控制台:Array[1]

console.log(new_devices.length)

结果在控制台:0

代码产生这样的:

var sp = require('serialport'); 
var new_devices = []; 

sp.list(function(err, ports) { 
    ports.forEach(function(current) { 
    if (current.manufacturer == "Teensyduino") { 
     new_devices.push(current); 
    } 
    }); 
}); 

console.log(new_devices); 
console.log(new_devices.length); 

enter image description here

+2

您需要发布代码重现了这个问题。到目前为止没有人能够重现这一点。数组旁边的“我”按钮说什么?是异步进行? – Xufox

+0

请使用StackSnippet发布代码 –

+0

不,没有任何异步。 – Alfo

回答

2

当控制台登录阵列控制台创建该数组的引用,它不会在执行时向您显示数组状态的快照。

(在代码项目被附加到列表异步,所以当控制台日志打印列表为空)。

考虑这个例子:

enter image description here

+0

那我该如何重组这个代码呢,这样我才能在控制台打印'new_devices.length'的时候得到一个正确的数字? – Alfo

+0

将console.log移动到ports.forEach之后 – knutesten