We can use concat()
to append element or event another array
to an array.
var colors = ["A", "B", "C"];
var colors2 = colors.concat("D", ["E", "F"]);
console.log(colors);
console.log(colors2);
The code above generates the following result.
The slice(), which gets the sub array, may accept one or two arguments: the starting and stopping positions.
var colors = ["A", "B", "C", "D", "E"];
var colors2 = colors.slice(1);
var colors3 = colors.slice(1,4);
console.log(colors);
console.log(colors2);
console.log(colors3);
The code above generates the following result.
We can use splice() to delete items from an array, by specifying the position of the first item to delete and the number of items to delete.
For example, splice(0, 2) deletes the first two items.
var colors = ["A", "B", "C", "D", "E"];
var colors2 = colors.splice(0,2);
console.log(colors); //C,D,E
The code above generates the following result.
We can use splice() to insert items to a specific position by providing three or more arguments: the starting position, 0 , and the items to insert.
var colors = ["A", "B", "C", "D", "E"];
var colors2 = colors.splice(2,0,"A","B","C");
console.log(colors); //A,B,A,B,C,C,D,E
The code above generates the following result.
splice() can do delete and insert at the same time and result in an replacement action. You specify three arguments: the starting position, the number of items to delete, and any number of items to insert.
For example, splice(2, 1, "A", "B") deletes one item at position 2 and then inserts the strings "A" and "B" into the array at position 2.
var colors = ["A", "B", "C"];
//insert two values, remove one
var removed = colors.splice(1, 1, "D", "E");
console.log(colors); //A,D,E,C
console.log(removed); //B
The code above generates the following result.
splice() returns an array that contains any items that were removed from the array or an empty array if no items were removed.