How to add an element into an array from differernt orders in Javascript?
Question
The is an array, and I wanna add an element at the beginning and the end of the array.
Answer
So the array is
1 | var array = [2, 3, 4]; |
The new element is var newBeginning = 1;
, and var newEnd = 5;
.
To the beginning
If we wanna at to the beginning, we can use unshift
function.
1 | array.unshift(newBeginning); // [1, 2, 3, 4] |
To the end
If we wanna at to the end, we can use push
function.
1 | array.unshift(newEnd); // [2, 3, 4, 5] |
Reference
This is the end of post