使用另一个变量值设置变量名 - Java 脚本

发布于 2024-08-20 20:29:00 字数 191 浏览 6 评论 0原文

我想从变量中获取一个值,然后将其用作另一个变量的名称。我得到这样的信息:

var eval(BodyWeight[i]["ExerciseTitle"]) = BodyWeight[i]["ExerciseVideo"]; 

这给了我一个错误,“丢失;”在声明之前”。

有什么想法吗?

I want to get a value from a variable then use that as the name for another variable. I got something like this:

var eval(BodyWeight[i]["ExerciseTitle"]) = BodyWeight[i]["ExerciseVideo"]; 

This is giving me an error, 'missing ; before statement'.

Any ideas?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

回眸一遍 2024-08-27 20:29:00

虽然 eval 将为您提供一种可变变量的形式,但它很混乱,并且可能会导致语法错误:

try {
    eval('var ' + BodyWeight[i]["ExerciseTitle"] + ' = BodyWeight[i].ExerciseVideo');
} catch () {
    // what to do here if BodyWeight[i]["ExerciseTitle"] isn't a valid variabe name?
}

最好使用对象属性而不是局部变量。

thing[BodyWeight[i].ExerciseTitle] = BodyWeight[i].ExerciseVideo;

While eval will give you a form of variable variables, it's messy and potentially leads to syntax errors:

try {
    eval('var ' + BodyWeight[i]["ExerciseTitle"] + ' = BodyWeight[i].ExerciseVideo');
} catch () {
    // what to do here if BodyWeight[i]["ExerciseTitle"] isn't a valid variabe name?
}

Better to use object properties rather than local variables.

thing[BodyWeight[i].ExerciseTitle] = BodyWeight[i].ExerciseVideo;
森末i 2024-08-27 20:29:00

如果您将当前包含在 eval 中的部分指定为属性,则会更容易。

var myvar = {};
myvar[BodyWeight[i]["ExerciseTitle"]] = BodyWeight[i]["ExerciseVideo"];

无需进行邪恶评估。

It will be easier if you specify the part you currently have enclosed in eval as a property.

var myvar = {};
myvar[BodyWeight[i]["ExerciseTitle"]] = BodyWeight[i]["ExerciseVideo"];

No evil eval necessary.

深爱成瘾 2024-08-27 20:29:00

如果我明白您希望实现什么:

var eval(BodyWeight[i]["ExerciseTitle"]) = BodyWeight[i]["ExerciseVideo"]; 

//to try and get
var BodyWeight4ExerciseTitle = BodyWeight[i]["ExerciseVideo"];
              ^-//guessing this is an iterator

要实现这一目标,只需执行以下操作:

var key = 'BodyWeight' + i + 'ExerciseTitle';
window[key] = BodyWeight[i]["ExerciseVideo"];

//now you have a global variable "BodyWeight4ExerciseTitle"

If I understand what you are hoping to accomplish:

var eval(BodyWeight[i]["ExerciseTitle"]) = BodyWeight[i]["ExerciseVideo"]; 

//to try and get
var BodyWeight4ExerciseTitle = BodyWeight[i]["ExerciseVideo"];
              ^-//guessing this is an iterator

To accomplish this, just do:

var key = 'BodyWeight' + i + 'ExerciseTitle';
window[key] = BodyWeight[i]["ExerciseVideo"];

//now you have a global variable "BodyWeight4ExerciseTitle"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文