js array Cheet Sheet [ 1127 views ]
Goal: Collect the array manipulation methods
1. add item to an array
unshift -> array <- push [/html] <strong>unshift</strong>: The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array. <strong>push</strong>: The push() method adds one or more elements to the end of an array and returns the new length of the array. <b>2. remove item from an array</b> [html] shift <- array -> pop
shift: The shift() method removes the first element from an array and returns that element. This method changes the length of the array.
pop: The pop() method removes the last element from an array and returns that element.
3. insert item to an array
There is no general solution to do this. Let's extend the array object with the insert method like this:
Array.prototype.insert = function(index) { index = Math.min(index, this.length); arguments.length > 1 && this.splice.apply(this, [index, 0].concat([].pop.call(arguments))) && this.insert.apply(this, arguments); return this; };
and the calling is:
["a", "b", "c"].insert(2, "V", ["X", "Y", "A"], "Z"); the result will be: ["a", "b", "V", "X", "Y", "A", "Z", "c"]