首页 > 解决方案 > 即使其中有数据,我的数组中的项目也未定义

问题描述

我正在通过 HTTP 请求中的 Info 动态分配一个数组。然后我尝试从该数组中的数据生成一些东西 - 我控制台.log'd 数组所以我知道其中有数据。然而,在遍历它时,每个键都是未定义的。

基本上,我从 REST 服务器返回的每个项目都有一个 ID 标记,表明它们以某种方式属于一起。我暂时称它为“SlotID”。

我会尽量保持简单。所以这里有一些剪裁。

let items = new Array(23); // The highest "SlotID" can be 22, and 0 isn't used.
fetch(URI)
.then(results => {
    return results.json();
}).then(data => {
    for (var itemKey in data.Results) {
        var item = data.Results[itemKey]; // This is all just the fetch.
        if (items[item.SlotID] != null) { // I'm creating a new Array for each SlotID here, and if that array is already created I'm pushing to it.
            items[item.SlotID].push(item);
          } else {
            items[item.SlotID] = [item];
          }
        }
    }
});

这(现在通过测试调用)填充 items[1]。我通过 console.log(items) 确认了一个数组;输出:

(23) [...] 1: (2) [...] 0: Object { BaseParamValue0: 19, BaseParamValue1: 21, BaseParamValue2: 23, ... } 1: Object { BaseParamValue0: 10, BaseParamValue1: 10, BaseParamValue2 : 17, ... } ​​长度:2 ​​:数组[]​长度:23​:[

所以我现在基本上有一个对象数组数组。

      for (var i = 0; i < 22; i++) {
        console.log(i + " " + items[i]);
      }

但是,这会将 1 输出为未定义,console.log(items[1]) 也输出未定义。为什么?

标签: javascriptarraysmultidimensional-array

解决方案


推荐阅读