2017-04-11 37 views
2

只要我需要做的是:如何在javascript中創建3/4 /多維數組?

var a = [[[]]]; 
a[1][2][3] = "hello!"; // [...[undefined,undefined,undefined,"hello!"]...]; 
a[1][2][1] = "a"; // [...[undefined,"a",undefined,"hello!"]...] 
a[2][3][4] = "new_index" // [...[undefined,"a",undefined,"hello!"]...[undefinedx4, "new_index"]] 

在我來說,我更喜歡,直到指定的索引沒有實例化數組的大小,並增加由較大的指數需要時的大小。 因爲js支持多維數組很弱,所以在javascript中最簡單或最乾淨的方法是什麼?

回答

1

在JS數組是引用類型,所以創建一個ND數組是棘手的。 cloninig工具將非常方便。因此,你可以這樣做:

Array.prototype.clone = function(){ 
 
    return this.map(e => Array.isArray(e) ? e.clone() : e); 
 
}; 
 
function arrayND(...n){ 
 
    return n.reduceRight((p,c) => c = (new Array(c)).fill().map(e => Array.isArray(p) ? p.clone() : p)); 
 
} 
 

 
var arr = arrayND (2,3,4,"x") 
 
console.log(JSON.stringify(arr));

初始參數定義尺寸和最後一個參數是填充值。

而這應該適用於ES6兼容的瀏覽器;

Array.prototype.clone = function(){ 
 
    return this.map(function(e){ 
 
        return Array.isArray(e) ? e.clone() : e; 
 
        }); 
 
}; 
 

 
function arrayND(){ 
 
    var n = Array.prototype.slice.call(arguments); 
 
    return n.reduceRight(function(p,c){ 
 
         return c = Array(c).fill().map(function(e){ 
 
                  return Array.isArray(p) ? p.clone() : p; 
 
                 }); 
 
         }); 
 
} 
 

 
var arr = arrayND (2,3,4,"x"); 
 
console.log(JSON.stringify(arr));

+1

@Dragon晚上我可能還沒有很清楚...... It'a所有關於初始化。如果你想......你可以用'undefined'來填充它們。問題是,一旦你創建了ND數組,那麼你可以通過執行'myArr [x] [y] ... [z ] =「whatever」 – Redu

+0

問題是,當我寫arrayND(3,4,5,「x」)時,它會生成你提到的,但是又一次我不能使用它。它覆蓋了前一個數組。當我增加索引或增加大小時,它也不會工作。每次都會覆蓋。 – DragonKnight

+1

@Dragon Night當你用'arr = arrayND(2,3,4,「x」)創建一個數組時,你創建了一個3D數組,像一個數組充滿了2個數組,每個數組填充4個項目('在這種情況下爲「x」)。當你喜歡'arr [1] [2] [3] =「test」''時,你將在主數組的第二個數組的第三個數組中的第四個項目分配''test「'。請嘗試。 – Redu

1

這裏是我的解決方案:

function assign(input) { 
 
    if ('object' !== typeof input) { 
 
     let tmp = {}; 
 

 
     tmp[input] = arguments[1]; 
 
     input = tmp; 
 
    } 
 

 
    let regex = /\.?([^.\[\]]+)|\[(\d+)]/g; 
 
    let result = {}; 
 

 
    for (let p in input) { 
 
     let data = result, prop = '', match; 
 

 
     while (match = regex.exec(p)) { 
 
      data = data[prop] || (data[prop] = (match[2] ? [] : {})); 
 
      prop = match[2] || match[1]; 
 
     } 
 

 
     data[prop] = input[p]; 
 
    } 
 

 
    return result['']; 
 
} 
 

 
// Example usage 
 
let a = assign('3[4][5]', 'hello'); 
 
let b = assign('3[4][5][6]', 'world!'); 
 
let c = assign('you.can.use.object.as.well', 'cool!'); 
 
let d = assign('or.mix[3].them[2]', 'together!'); 
 
let e = assign({'with.multiple': 'properties', 'in.a.single': 'object'}); 
 

 
let f = assign({ 
 
    '[1][2][3]': "hello!", 
 
    '[1][2][1]': "a", 
 
    '[2][3][4]': "new_index" 
 
}); 
 

 
console.log(a[3][4][5], '->', JSON.stringify(a)); 
 
console.log(b[3][4][5][6], '->', JSON.stringify(b)); 
 
console.log(c.you.can.use.object.as.well, '->', JSON.stringify(c)); 
 
console.log(d.or.mix[3].them[2], '->', JSON.stringify(d)); 
 
console.log(e.with.multiple, '->', e.in.a.single, '->', JSON.stringify(e)); 
 

 
console.log('f[1][2][3]:', f[1][2][3]); 
 
console.log('f[1][2][1]:', f[1][2][1]); 
 
console.log('f[2][3][4]:', f[2][3][4]);

+0

感謝您的回答。我試圖改進我的問題和例子。請你看看。 – DragonKnight

+0

@DragonKnight我更新了示例以向您展示如何在您的用例中使用assign函數。 –