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
1.5k views
in Technique[技术] by (71.8m points)

dynamic array names javascript

I have a few arrays with like names.

ArrayTop[]  
ArrayLeft[]   
ArrayRight[]  
ArrayWidth[]

I am trying to set the name dynamically in a function and then set value.

I have tried many ways of dynamically picking the right array but have not come up with a solution.

function setarray(a,b,c){
    eval(Array+a+[b])=c
}

setarray('Top',5,100)

In this example i am trying to set.

ArrayTop[5]=100
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

If you are doing this in the browser, one possible solution would be to do:

function setArray(a, b, c){
    window['Array' + a][b] = c;
}

setArray('Top', 5, 100);

I would recommend that all your array's be contained in some object and not pollute the global namespace. So it would be more like:

var arrays = {
    ArrayTop: [],
    ArrayNorth: []
};

function setArray(a, b, c){
    arrays['Array' + a][b] = c;
}

setArray('Top', 5, 100);

I would not recommend using eval. Eval is not meant for this kind of dynamic evaluation and it is a huge performance hit.


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

...