Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
378 views
in Technique[技术] by (71.8m points)

arrays - Javascript = Building a variable name from strings

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];
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...