简体   繁体   中英

Insert a row of elements into a multi-dimensional array based on index

Insert a row of elements into a multi-dimensional array based on index

For Example:

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

The last line in my code didn't work. I am not sure if the rest of the code is right neither.

Now can anyone please let me know whether I can insert a row of elements somewhere in between and move the remaining elements one index down?

You accidently wrote new Array{} which is wrong - your command should be either:

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

or even better

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

Altogether, in javascript the new Array() notation should be avoided (js automatically controls the dimension of it's arrays, no need to preallocate or declare it). Instead you can write:

MultiArray = [];

So, you can directly write:

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

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

尝试:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM