dynamic array names javascript

后端 未结 7 818
南笙
南笙 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:20

    Hash map will be a perfect tool:

    var arrays = {
      top: [],
      left: [],
      right: [],
      bottom: []
    };
    
    function addToArray(name, index, value) {
      arrays[name][index] = value;
    }
    
    addToArray('top', 5, 100);
    

    I took the liberty to give more explicit names.

    I suggest also two good practices:

    • do not use eval. Eval is not meant for this kind of dynamic evaluation. In your case, it's a performance killer

    • do not polute the global namespace. In browser environnement, avoid adding stuff to window (which is global).

    0 讨论(0)
提交回复
热议问题