使用变量名和字符串组合创建 Javascript 变量 [英] Create Javascript Variable with name of a variable and string combined

查看:23
本文介绍了使用变量名和字符串组合创建 Javascript 变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我似乎无法解决这个问题,这就是我所拥有的...

I cant seem to solve this problem, heres what I have...

vid1=0;
vid2=0;
vid3=0;

num=1;

'vid'+num = 1;
// vid1=1;

我想根据数字创建变量,所以如果数字是2,那么就以vid2的名字创建一个变量,并将其设置为1.

I want to create the variable based on the number, so if the number is 2, then make a variable by the name of vid2 and set it equal to 1.

PS:这是我第一次使用 stackoverflow,很抱歉,如果我在本网站的传统方面犯了任何错误 =) 提前致谢.

PS: This is my first time on stackoverflow, so sorry if I made any mistakes in terms of tradition on this website =) And thannks in advanced.

推荐答案

如果您在全局命名空间中,请使用:

If you're in the global namespace, use this:

window['vid' + num] = 1;

但这是一个非常好的数组用例:

but this is a really good use case for an array:

var numbers = [0, 0, 0];
var num = 1;

numbers[num] = 1;

这篇关于使用变量名和字符串组合创建 Javascript 变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆