= JavaScript的字符串的构建变量名 [英] Javascript = Building a variable name from strings
问题描述
让我们说我有:
VAR acDeMa = [10,20,30,40,50];
VAR TEST1 = 5;VAR测试2 = 7;VAR TEST3 = 3;VAR piece1;VAR piece2;VAR piece3;如果(test1的== 5)
{piece1 =AC;}如果(test1的== 7)
{piece2 =德;}如果(test1的== 3)
{piece3 =麻;}
我如何再结合这些片段,承认它是从早期的阵列,并从我的数组复制值到一个新的阵列?
VAR finishedArray =(piece1 + piece2 + piece3);
我想下面这个效果,基本上,但无需专门键入它的名字(acDeMa):
VAR finishedArray = acDeMa;
我将如何去这样做呢?这样做的原因,这是因为我有大约60阵列和我在一个时间比较两个。有些阵列有共同的东西,所以,而不是有独立60'如果'的语句,我会使用如果语句(即巧妙地查找各种阵列的共同点)几个选择在一起,而那条正确的数组名,然后使用我的数组。
没有,我不希望有数字5,7和3的新数组。我想要的数字:10,20,30,40,在finishedArray 50,但由于这些数字可能每次都不同,我不想写的:
VAR finishedArray = acDeMa;
或
VAR finishedArray = [10,20,30,40,50];
并不推荐使用,但如果你是在全球范围内的工作,你可以使用这样的窗口对象
VAR finishedArray =窗口[piece1 + piece2 + piece3];
这将创建到原来的数组的引用。为了得到一个单独副本使用片
法
VAR finishedArray =窗口[piece1 + piece2 + piece3] .slice(0)
Let's say I have:
var acDeMa = [10, 20, 30, 40, 50];
var test1 = 5;
var test2 = 7;
var test3 = 3;
var piece1;
var piece2;
var piece3;
if ( test1 == 5 )
{piece1 = "ac";}
if ( test1 == 7 )
{piece2 = "De";}
if ( test1 == 3 )
{piece3 = "Ma";}
How do I then combine those pieces, recognise it as the Array from earlier, and copy the values from my Array into a new Array?
var finishedArray = (piece1 + piece2 + piece3);
I want this effect below, basically, but without having to specifically type it's name (acDeMa):
var finishedArray = acDeMa;
How would I go about doing this? The reason for doing this is because I have about 60 arrays and I'm comparing two at a time. Some of the arrays have things in common, so rather than have 60 separate 'if' statements, I'd rather piece the correct Array name together using a few choice 'if' statements (that cleverly find what various Arrays have in common), and then using that as my Array.
No, I do not want to have the numbers 5, 7, and 3 in a new Array. I want the numbers: 10, 20, 30, 40, 50 in finishedArray, but because those numbers could be different every time, I DON'T want to write:
var finishedArray = acDeMa;
or
var finishedArray = [10, 20, 30, 40, 50];
Not really recommended but if you are working in the global context you could use the window object like this
var finishedArray = window[piece1+piece2+piece3];
That will create a reference to your original array. To get a separate copy use the slice
method
var finishedArray = window[piece1+piece2+piece3].slice(0)
这篇关于= JavaScript的字符串的构建变量名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!