Javascript数组有数据但长度为零

标签 javascript arrays

编辑:由于我没有正确理解 promise ,这似乎是一个同步问题。我假设“.then”等待 promise 解决。显然事实并非如此。

我遇到了一个以前从未见过的奇怪错误。

我有这段代码,它在 Chrome 控制台中生成以下输出。

显然它是一个数组,并且有数据和长度,但是当我打印长度属性时它为零。 (我也无法用 map 迭代它)

我真的很困惑,任何帮助将不胜感激。

const readFile = (file) => (
  new Promise((resolve) => {
    const fr = new FileReader();
    fr.onload = () => {
      resolve(fr.result);
    };
    fr.readAsText(file);
  })
);

const readFiles = (files) => {
  const readFiles = [];
  files.forEach((file) => (readFile(file)).then((data) => readFiles.push({name: file.name, data })));
  return readFiles;
};

const scenes = readFiles(...grabbed from file picker dialog...)
console.log('scenes: ', ui.value.scenes);
console.log('length: ', ui.value.scenes.length);

console

最佳答案

从读取文件返回的是一个 promise ,因此您应该像这样读取 then 方法中的解析值

 readFile().then( (scenes) => {
     console.table(scenes)
 }

您可以在控制台中看到值的原因是,在 Chrome 和 Firefox 中使用 console.log 时,它是对象的实时版本,以后可能会更改代码(来自 promise 解析)。
如果您想及时打印对象的状态,您可以运行console.log(JSON.stringify(obj)) 这是 MDN 的片段

Please be warned that if you log objects in the latest versions of Chrome and Firefox what you get logged on the console is a reference to the object, which is not necessarily the 'value' of the object at the moment in time you call console.log(), but it is the value of the object at the moment you click it open.

关于Javascript数组有数据但长度为零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49838329/

相关文章:

javascript - .each() 返回的问题(对象数 x 值)

javascript - Node.js puppeteer - 如何从表中仅获取某些(过滤器)记录

javascript - SPA 中刷新 token Cookie 的 CSRF 保护

javascript - 对隐藏元素感到困惑

php - 将 csv 文件转换为 PHP 二维数组

连接两个字符串数组?

javascript - 在 cURL 中传递编码链接

javascript - ZingChart 样式或删除来自 CSV 的饼图标签

arrays - Swift - '[Subject] does not have a member named ' 名称' '

PHP:根据值列表对多维数组进行排序