gpt4 book ai didi

javascript - 命名;在javascript中动态创建变量

转载 作者:行者123 更新时间:2023-12-01 02:32:07 27 4
gpt4 key购买 nike

为了避免 JavaScript 堆问题,我使用多个数组:family1、family2、family3 ...、dogs1、dogs2、dogs3 ... 使用示例:“family1 和 dogs1”或“family132 和 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);

}

}

最佳答案

您正在寻找:

let str = this['family'+id]; 

但这通常是一个糟糕的设计模式。不要用增量数字来命名变量。使用二维数组(即以数组作为值的数组),例如 this.dog[id][i]。如果您遇到“JavaScript 堆问题”,那么它是由其他代码引起的。

关于javascript - 命名;在javascript中动态创建变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48239427/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com