How do I efficiently create multi-dimensional javascript array?

独自空忆成欢 提交于 2020-01-06 12:25:08

问题


I need to store information similar to this:

tag_array['design1']['0'][0]['x'] = 100;
tag_array['design1']['0'][0]['y'] = 100;
tag_array['design1']['0'][0]['w'] = 710;
tag_array['design1']['0'][0]['h'] = 332;

This would work if it is PHP but it's not working in javascript.

How do I create the same array in proper javascript syntax?


回答1:


In PHP, you can do that because it will make the parent elements too (it actually throws a warning). In JavaScript, it will error out because the parent elements don't exist.

Instead of making it like that, try to make it all at once like this:

var tag_array = {
    design1: {
        '0': [{
            x: 100,
            y: 100,
            w: 710,
            h: 332
        }]
    }
};

This should give you the structure you want.

UPDATE: Answer has been updated to reflect the fact that the 1st 0 can be a string.




回答2:


If you want to do it programatically then because JavaScript requires you to have this type of structure

tag_array = {};
tag_array['design1'] = {};
tag_array['design1']['0'] = [];
tag_array['design1']['0'][0] = {};
tag_array['design1']['0'][0]['x'] = 100;

you can make a prototype function to create the object/array structure for you

Object.defineProperty(Object.prototype, 'addDimensions', { value: function(){
    var prop = arguments[0];
    if(this[prop] !== undefined){
        if(typeof this[prop] !== 'object') throw 'Property "'+prop+'" is already defined.'
    }else{
        if(arguments.length > 1 && ~~arguments[1] === arguments[1] && arguments[1] >= 0) this[prop] = [];
        else this[prop] = {};
    }
    if(arguments.length > 1){
        this[arguments[0]].addDimensions.apply(
            this[arguments[0]],
            Array.prototype.slice.call(arguments,1)
        );
    }
    return this;
},
enumerable: false });

and call it on an empty object {}

var myArrayLikeObject = ({}).addDimensions('design1','0',0); // {design1: [ [ {} ] ] }

or an array [] (only if first arg is an integer)

var myMultiArray = [].addDimensions(0,'hi',0); // [ {hi: [ {} ] } ]

or on an existing array or object

var a = [0,1,2];
a.addDimensions(3,0); // a = [0, 1, 2, [ {} ] ]


来源:https://stackoverflow.com/questions/12287490/how-do-i-efficiently-create-multi-dimensional-javascript-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!