Javascript数组计数与控制台不一致? [英] Javascript Array count doesn't agree with console?

查看:82
本文介绍了Javascript数组计数与控制台不一致?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里很蠢吗? (我来自Ruby,因此可能缺少有关Javascript数组的内容.)

Am I being stupid here? (I'm coming from Ruby, so there might be something about Javascript arrays that I'm missing).

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);

推荐答案

在控制台日志数组时,控制台会创建对该数组的引用,但不会向您显示执行时该数组状态的快照.

When you console log arrays the console creates a reference to that array, it does not show you a snapshot of the state of the array at the point of execution.

(在您的代码项中,异步将其追加到列表中,因此在控制台日志打印时,列表为空.)

(In your code items are appended to the list async, so when the console log is printing the list is empty.)

请考虑以下示例:

这篇关于Javascript数组计数与控制台不一致?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆