2016-09-17 68 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