Array functions in javascript
[].splice
Removes elements from an array, returns the removed items as an array, and optionally replaces the items.
Definition
array.splice(start[, deleteCount[, item1[, item2[, ...]]]])
Sample Code
var arr = [1, 2, 3, 4, 5];
var result = arr.splice(1, 2, "A", "B", "C");
console.log(arr); // [1, "A", "B", "C", 4, 5]
console.log(result); // [2, 3]
Reference
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice
[].slice
Returns a sub-array, leaving the original array as-is. Use negative begin value as an offset from the last element.
Definition
arr.slice([begin[, end]])
Sample Code
var arr = [1, 2, 3, 4, 5];
var result = arr.slice(2, 4);
console.log(arr); // [1, 2, 3, 4, 5]
console.log(result); // [3, 4]
Reference
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice
[].shift
Removes the first element of an array and returns it. The original array is modified. This can be used to treat an array as a queue (first in, first out).
Definition
arr.shift()
Sample Code
var arr = [1,2,3];
while (arr.length) {
let val = arr.shift();
console.log(val); // 1, then 2, then 3
}
console.log(arr); // []
Reference
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift
[].unshift
Inserts one or more items to the beginning of an array. It returns the new array count.
Definition
arr.unshift(element1[, ...[, elementN]])
Sample Code
var arr = [1,2,3,4];
var x = arr.unshift("a", "b"); // arr = ["a","b",1,2,3,4], x=6
Reference
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/unshift
[].push
Adds one or more items to the end of an array. It returns the new array count.
Definition
arr.push(element1[, ...[, elementN]])
Sample Code
var arr = [1,2,3,4];
var x = arr.push("a", "b"); // arr = [1,2,3,4,"a","b"], x=6
Reference
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push
[].pop
Removes the last element of an array and returns it. The original array is modified. This can be used to treat an array as a stack (last in, first out).
Definition
arr.pop()
Sample Code
var arr = [];
arr.push(1);
arr.push(2);
arr.push(3);
while (arr.length) {
let x = arr.pop();
console.log(x); // 3, then 2, then 1
}
console.log(arr); // []
Reference
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/pop
Browser Requirements
These all are basic array functions, and work on all browsers.
Comments
Post a Comment