dynamic array names javascript

后端 未结 7 862
南笙
南笙 2020-12-19 07:25

I have a few arrays with like names.

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

I am trying to set the name dynamically in a f

7条回答
  •  佛祖请我去吃肉
    2020-12-19 08:12

    Put all your arrays into an object:

    var myArrays = { 
        top : arrayTop,
        left: arrayLeft,
        right: arrayRight,
        bottom: arrayBottom
    }
    

    And the to get an array you can just:

    myArrays["top"][5] = 100;
    

    Or you can skip defining the arrays as global variables and just do something like:

    var myArrays = { 
        top : [],
        left: [],
        right: [],
        bottom: []
    }
    

    Which initializes 4 empty arrays which you can populate:

    myArrays["top"][0] = 100;
    

    or

    myArrays.top[0] = 100;
    

    However, if top, left, right and bottom all are related (refering to the same object), it might make more sense to create an object with those properties and create a single array of those objects:

    function MyObj(top, left, right, bottom) {
       this.top = top;
       this.left = left;
       this.right = right;
       this.bottom = bottom;
    }
    
    var myArray = [];
    
    myArray.push(new MyObj(1,2,3,4));
    console.log(myArray[0]);
    
    myArray[0].left = 7;
    console.log(myArray[0]);
    

    http://jsfiddle.net/UNuF8/

提交回复
热议问题