根据索引将一行元素插入到多维数组中

时间:2012-11-06 12:31:53

标签: javascript

根据索引

将一行元素插入多维数组中

例如:

MultiArray = new Array(5);

MultiArray [0] = new Array(2);

MultiArray [0][0] = "Tom";

MultiArray [0][1] = "scientist";


MultiArray [1] = new Array(3);

MultiArray [1][0] = "Beryl";

MultiArray [1][1] = "engineer";

MultiArray [1][2] = "Doctor";

MultiArray [2] = new Array(2);

MultiArray [2][0] = "Ann";

MultiArray [2][1] = "surgeon";

MultiArray [3] = new Array(2);

MultiArray [3][0] = "Bill";

MultiArray [3][1] = "taxman";

MultiArray [4] = new Array(2);

MultiArray [4][0] = "Myrtal";

MultiArray [4][1] = "bank robber";

MultiArray.splice(1,0, new Array(2){"two","one"});

我的代码中的最后一行不起作用。我不确定其余代码是否正确。

现在任何人都可以告诉我是否可以在其间插入一行元素并将其余元素向下移动一个索引?

2 个答案:

答案 0 :(得分:4)

你意外地写了new Array{}这是错误的 - 你的命令应该是:

MultiArray.splice(1,0, new Array(2)("two","one")); // no curled brackets!!

甚至更好

MultiArray.splice(1,0, ["two","one"]);

总而言之,在javascript中应避免使用new Array()表示法(js会自动控制其数组的维度,无需预先分配或声明它)。相反,你可以写:

MultiArray = [];

所以,你可以直接写:

MultiArray = [[ "Tom","scientist"],["Beryl","engineer","Doctor"],
              ["Ann","surgeon"],["Bill","taxman"],["Myrtal","bank robber"]];

MultiArray.splice(1,0, ["two","one"]);

答案 1 :(得分:2)

尝试:

MultiArray.splice(1,0, ["two","one"]);