gpt4 book ai didi

javascript - 循环访问对象时,如何以编程方式创建同名变量?

转载 作者:行者123 更新时间:2023-11-28 13:03:16 25 4
gpt4 key购买 nike

我有一些看起来像这样的对象,但列出了几辆车

let snapshot = [
{
"vehicle": "2015 Ford Mustang EcoBoost Premium",
"link": "details9.html",
"img": "css/images/vehicles/progressiveJPG/spotlight-mustang2.jpg",
"trim": "GT Premium 2dr Coupe",
"price": 16998,
"priceSpecial": 19000,
"priceAvg": 21470,
"priceMonthly": 253,
"miles": 37132,
"milesAvg": 31029
}
]

然后我想循环使用这样的东西

for (var i = 0; i < snapshot.length; i++) {
let vehicle = snapshot[i].vehicle;
let link = snapshot[i].link;
let img = snapshot[i].img;
let trim = snapshot[i].trim;
let price = snapshot[i].price;
let priceSpecial = snapshot[i].priceSpecial;
let priceAvg = snapshot[i].priceSpecial;
let priceMonthly = snapshot[i].priceMonthly;
let miles = snapshot[i].miles;
let milesAvg = snapshot[i].milesAvg;
}

然后,我将使用模板字符串配置输出,并在需要时插入这些变量。我的问题是,我可以动态创建这些与对象键同名的变量吗?或者是否有必要。例如,我是否应该将每个项目称为 snapshot[i].vehicle

最佳答案

My question is, can I dynamically create these variables that have the same name as the object key or is it even necessary. Should I just refer to each item as snapshot[i].vehicle for instance?

您目前做得很好

for (var i = 0; i < snapshot.length; i++) {
let vehicle = snapshot[i].vehicle;

console.log(vehicle)
console.log(snapshot[i].vehicle)
}

上面的代码两次打印出相同的值,只是通过不同的句柄

您是否应该将所有属性放入相应的变量中,或者是否应该直接引用 snapshot[i] 基本上取决于您。当代码变得太困惑而无法轻松阅读时,我通常会选择变量解决方案。

我建议您为了可读性而编写代码,而不是为了某些效率概念而编写代码,否则无论如何也不会让您的脚本运行明显更快

关于javascript - 循环访问对象时,如何以编程方式创建同名变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48809928/

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