首页 > 解决方案 > Iterating a Multidimensional Array in TypeScript

问题描述

I am having trouble iterating through a multidimensional array in TypeScript. In order to store the data into a db, I need to convert the multidimensional array into a one dimensional one.

My function:

storeDevices() {
    let tempDeviceList: Device[][] = this.dataStorageService.getDevices();
    console.log(tempDeviceList);
    console.log(tempDeviceList[1]);
    console.log(tempDeviceList[1][1]);
    console.log(tempDeviceList.length);
  }
console.log(tempDeviceList);

results in https://pastebin.com/mb2B9yrM I am using this as a lookup table which is why the first element is often null.

I do not understand why

    console.log(tempDeviceList[1]); //undefined
    console.log(tempDeviceList[1][1]); //undefined
    console.log(tempDeviceList.length); //0

result in undefined and 0. Because of this I am not able to iterate over the array. Based on the printed JSON, those elements should exist.

标签: typescriptmultidimensional-arrayiteration

解决方案


Converting a multi-dimensional array into a single dimensional one is also known as array flattening. There's plenty of resources on this topic, here's one on SO to get you started.


推荐阅读