簡體   English   中英

如何有效創建多維javascript數組?

[英]How do I efficiently create multi-dimensional javascript array?

我需要存儲與此類似的信息:

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;

如果它是PHP,但不能在javascript中使用,則可以使用。

如何使用正確的JavaScript語法創建相同的數組?

在PHP中,您可以這樣做,因為它也會成為父元素(實際上會引發警告)。 在JavaScript中,由於父元素不存在,它將出錯。

與其像那樣制作,不如嘗試一下將其全部制作成這樣:

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

這應該為您提供所需的結構。

更新 :答案已經更新,以反映1st 0可以是字符串的事實。

如果要以編程方式進行操作,則因為JavaScript要求您具有這種類型的結構

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

您可以制作一個prototype函數來為您創建對象/數組結構

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 });

並在一個空對象{}上調用它

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

或數組[] (僅當第一個arg是整數時)

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

或在現有數組或對象上

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM