Append, sub array, remove elements in an array
Append
We can use concat()
to append element or event another array
to an array.
- When no arguments are passed in, concat() clones the array and returns it.
- If one or more arrays are passed in, concat() appends each item in these arrays to the end of the result.
- If the values are not arrays, they are simply appended to the end of the resulting array.
- The original array remains unchanged.
var colors = ["A", "B", "C"];
var colors2 = colors.concat("D", ["E", "F"]);
//www . j av a 2s . co m
console.log(colors);
console.log(colors2);
The code above generates the following result.
sub array
The slice(), which gets the sub array, may accept one or two arguments: the starting and stopping positions.
- For one argument, the method returns items between that position and the end of the array.
- For two arguments, returns items between the start and the end, not including the item in the end position.
- If either argument is a negative number, then the number is subtracted from the length of the array to determine the locations. calling slice(-2, -1) on an array with five items is the same as slice(3, 4).
- If the end position is smaller than the start, then an empty array is returned.
- The original array remains unchanged.
var colors = ["A", "B", "C", "D", "E"];
var colors2 = colors.slice(1);
var colors3 = colors.slice(1,4);
//from www.j a v a2 s . co m
console.log(colors);
console.log(colors2);
console.log(colors3);
The code above generates the following result.
Deletion
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.
Insertion
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");
//from w w w . j av a2s . c om
console.log(colors); //A,B,A,B,C,C,D,E
The code above generates the following result.
Replacement
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
//from w w w .j a va 2s.com
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.