【发布时间】:2018-01-13 11:29:24
【问题描述】:
为避免 javascript 堆问题,我使用多个数组:family1、family2、family3 ...、dogs1、dogs2、dogs3 ... 使用示例:“family1 and dogs1”或“family132 and dogs132”来创建一个新数组“结果”。
如何正确传递“id”
let id = 'value here'
this.family + id
this.dogs + id
到目前为止,我的 str 本身被推入新数组:t-h-i-s-.-f-a-m-i-l-y-1
for (let i = +0; i < +20; i++) {
const id = 1;
let str = 'this.family'+id; // ?
let str = 'this.dogs'+id; // ?
console.log(str);
const result = {
familyType: str[i], // behavior: t-h-i-s-.-f-a-m-i-l-y-1
protocol: this.dogs1[i], // expected original behavior
};
results.push(result);
}
}
【问题讨论】:
-
使用bracket notation。如
this['family'+id] -
这对我来说就像一个XY problem。为什么你认为存在“堆问题”?
-
@Khauri - 谢谢,这是正确的。
-
@Andreas - 这确实是一个 XY 问题:它与 npm 和/或 typescript 和/或 webpack 有关,但还没有通用的解决方案。我的应用程序只有一个 service.ts 有两个长度为 5000 的数组,我正在创建一个长度为 20 的新数组 - 这应该没问题。作为回应,我创建了多个短数组,它现在正在工作。
标签: javascript arrays variables naming