简体   繁体   English

TypeScript无法迭代关联数组

[英]TypeScript not able to iterate associative array

I have a service which populates my associative array in typescript, 我有一项服务,可在打字稿中填充我的关联数组,

fun populateData(){
let tempArr;
tempArr = [];
this.service.get('Post', 1, 'true').subscribe(
        (response) => {
          this.loadingIcon = false;

          for (let i = 0; i < response.results.length; i++) {
             tempList = response.results[i]['tags'];
             for ( let iter of tempList){
               if ( iter in tempArr) {
                 tempArr[iter] = tempArr[iter] + 1;
               }else {
                 tempArr[iter] = 1;
               }
             }
          }
        },
        (error) => {
          if (error['status'] === 401) {
            localStorage.clear();
            this.router.navigateByUrl('/login');
          } else {
            this.router.navigateByUrl('/error');
          }
        }
      );
      console.log(tempArr);
        /*
          This function is inside a class, once I iterate get access to tempArr I will be assigning the tempArr data to a class variable like

       for (items in tempArr){
            this.data.push(items, tempArr[items]);
       }
        */
}

I'm able to populate my associative array with the service above which gives the following output in console, 我可以使用上面的服务填充关联数组,该服务在控制台中提供以下输出,

控制台日志输出中的tempArr

I'm not able to iterate through this array, I tried a couple of methods like the following, 我无法遍历此数组,我尝试了以下几种方法,

for ( const key in tempArr) {
      console.log(key + ':' + tempArr[key]);
    }

I want both they key and values from the array. 我想要它们的键和值都来自数组。

TypeScript generally assumes that the keys to arrays are numbers. TypeScript通常假定数组的键是数字。 What you were doing might work but it's not very idiomatic. 您正在执行的操作可能会奏效,但不是很习惯。 I'm not going to rewrite your whole function but here are a few pointers: 我不会重写您的整个函数,但是这里有一些指针:

When constructing your associative array (map for short from now on) you should try using an object instead of an array: 在构造关联数组(从现在开始简称为映射)时,应尝试使用对象而不是数组:

const tagCounts: { [key: string]: number } = {};
for (const result of response.results) {
    for (const tag of result.tags) {
        tagCounts[tag] = (tagCounts[tag] || 0) + 1;
    }
}

Then you can iterate the result with: 然后,您可以使用以下方法迭代结果:

for (const tag of Object.keys(tagCounts)) {
    const count = tagCounts[tag];
    // Other stuff here
}

Or if you have polyfills for Object.entries then with: 或者,如果您有用于Object.entries则可以使用:

for (const [tag, count] of Object.entries(tagCounts)) {
    // Other stuff here
}

Looking at your code, this.data.push also seems wrong: it will add a string and a number to your data array which is almost certainly not what you want. 查看您的代码, this.data.push也似乎是错误的:它将为data数组添加一个字符串和一个数字,这几乎肯定不是您想要的。 You might want to consider converting data to an object as well if you want to store key-value pairs. 如果要存储键值对,则可能还需要考虑将data转换为对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM