有一個嵌套數組,其應該代表一些表數據:JS:在嵌套陣列,其表示表中的數據添加和刪除元素
var array = [
[ "r1c1", "r1c2", "r1c3" ],
[ "r2c1", "r2c2", "r2c3" ],
[ "r3c1", "r3c2", "r3c3" ]
]
現在我需要陣列結構操縱到
- 添加新的列或行(用於第一和第二實施例之間的新列)
- 刪除特定的行或列
移除一行應該是很簡單的
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" ]
]
因此,要保持它一般'1'應該是一個變量('index')和'0'是'指數1'? – user3142695
@ user3142695否,'1'應該是'index','0'應該是'0'(因爲你不想刪除任何元素) – madox2