0

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

例如:

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

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

现在谁能告诉我是否可以在中间的某处插入一行元素并将剩余的元素向下移动一个索引?

4

2 回答 2

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"]);
于 2012-11-06T12:41:43.647 回答
2

尝试:

MultiArray.splice(1,0, ["two","one"]);
于 2012-11-06T12:40:46.137 回答