Javascript using variable as array name

后端 未结 5 1107
醉话见心
醉话见心 2020-12-18 15:29

I have several arrays in Javascripts, e.g.

a_array[0] = \"abc\";
b_array[0] = \"bcd\";
c_array[0] = \"cde\";

I have a function which takes the arra

相关标签:
5条回答
  • 2020-12-18 16:12

    Why can't you just pass the array?

    function perform(array){
        alert(array[0]);
    }
    perform(a_array);
    perform(b_array);
    perform(c_array);
    

    Or am I misunderstanding the question...

    0 讨论(0)
  • 2020-12-18 16:23

    You can either pass the array itself:

    function perform(array) {
        alert(array[0]);
    }
    perform(a_array);
    

    Or access it over this:

    function perform(array_name) {
        alert(this[array_name][0]);
    }
    perform('a_array');
    
    0 讨论(0)
  • 2020-12-18 16:23

    Instead of picking an array by eval'ing its name, store your arrays in an object:

    all_arrays = {a:['abc'], b:['bcd'], c:['cde']};
    function perform(array_name) {
        alert(all_arrays[array_name][0]);
    }
    
    0 讨论(0)
  • 2020-12-18 16:24

    I believe any variables you create are actually properties of the window object (I'm assuming since you used alert that this is running in a web browser). You can do this:

    alert(window[array_name][0])
    
    0 讨论(0)
  • 2020-12-18 16:28

    why don't you pass your array as your function argument?

    function perform(arr){
        alert(arr[0]);
    }
    
    0 讨论(0)
提交回复
热议问题