2016-11-11 39 views
2

有一個嵌套數組,其應該代表一些表數據:JS:在嵌套陣列,其表示表中的數據添加和刪除元素

var array = [ 
    [ "r1c1", "r1c2", "r1c3" ], 
    [ "r2c1", "r2c2", "r2c3" ], 
    [ "r3c1", "r3c2", "r3c3" ] 
] 

現在我需要陣列結構操縱到

  1. 添加新的列或行(用於第一和第二實施例之間的新列)
  2. 刪除特定的行或列

移除一行應該是很簡單的

array.splice(index, 1); 

要刪除的專欄中,我會覺得我必須遍歷數組throught:

array.forEach(row => { 
    row.splice(index, 1); 
}); 

但我認爲在這裏失去了一些東西。

對我來說,主要問題是添加一行或一列:要添加一個新行,我可以使用array.push(["new", "new", "new"])array.unshift(["new", "new", "new"]),但我應該如何在兩行之間添加一行?

預期結果

添加行具有索引= 1應導致:

array = [ 
    [ "r1c1", "r1c2", "r1c3" ], 
    ["new", "new", "new"], 
    [ "r2c1", "r2c2", "r2c3" ], 
    [ "r3c1", "r3c2", "r3c3" ] 
] 

添加柱具有索引= 1應導致:

array = [ 
    [ "r1c1", "new", "r1c2", "r1c3" ], 
    [ "r2c1", "new", "r2c2", "r2c3" ], 
    [ "r3c1", "new", "r3c2", "r3c3" ] 
] 

回答

3

您可以使用Array.prototype.splice()功能:

var arr = [ "r1c1", "r1c2", "r1c3" ]; 
// delete 0 elements and then add "new" element at 1 position 
arr.splice(1, 0, "new"); 
console.log(arr); [ "r1c1", "new", "r1c2", "r1c3" ]; 

因此,它可能看起來像:

var array = [ 
    [ "r1c1", "r1c2", "r1c3" ], 
    [ "r2c1", "r2c2", "r2c3" ], 
    [ "r3c1", "r3c2", "r3c3" ] 
]; 

// adding column 
array.forEach(arr => arr.splice(1, 0, "new")); 

// adding row 
array.splice(1, 0, ["new", "new", "new"]) 
+0

因此,要保持它一般'1'應該是一個變量('index')和'0'是'指數1'? – user3142695

+0

@ user3142695否,'1'應該是'index','0'應該是'0'(因爲你不想刪除任何元素) – madox2

0

您可以爲所有操作的一個功能。

  1. n是位置插入或刪除
  2. col_rowcolumnrow或。可以是adddelete
  3. insert是可選參數,如果您要添加新的行或列。

var array = [ 
 
    ["r1c1", "r1c2", "r1c3"], 
 
    ["r2c1", "r2c2", "r2c3"], 
 
    ["r3c1", "r3c2", "r3c3"] 
 
]; 
 

 
function addColumn(n, col_row, change, insert = 'new') { 
 
    if (col_row == 'column') { 
 
    array.forEach(function(e, i) { 
 
     if (change == 'add') { 
 
     e.splice(n, 0, insert); 
 
     } else if (change == 'delete') { 
 
     e.splice(n, 1); 
 
     } 
 
    }) 
 
    } else { 
 
    if (change == 'add') array.splice(n, 0, insert); 
 
    if (change == 'delete') array.splice(n, 1); 
 
    } 
 

 
    console.log(array) 
 
} 
 

 
addColumn(1, 'column', 'add', 'Lorem ipsum') 
 
addColumn(2, 'column', 'delete') 
 
addColumn(2, 'row', 'add', Array(3).fill('new'))

相關問題