1. 程式人生 > >10 common Array methods in JS

10 common Array methods in JS

var arr = ["a","b","c"];

arr.push("d");
//just adds a new element into the end of an array
console.log(arr); // ["a","b","c","d"]

//arr.pop();
//it removes the element in an array and returns that element
console.log(arr.pop()); // "d"
console.log(arr); // ["a","b","c"]

//concat()
//concatenates two arrays
var arr2 = ["g"
,"q"]; console.log(arr.concat(arr2)); // ["a","b","c","d","g","q"] //join() console.log(arr.join("")); // "abc" console.log(arr); //["a","b","c"] //reverse() console.log(arr.reverse()); //["c","b","a"] console.log(arr); //["c","b","a"] //shift() //it's going to remove the first element in the array and return that element console.log(arr.shift()); // "c"
console.log(arr); //["b","a"] //unshift() //it adds a new element to the beginning of your array and returns the length of the modified array console.log(arr.unshift("p")); // 3 console.log(arr); //["p","b","a"] //slice() console.log(arr.slice(1,2)); // ["b"] console.log(arr.slice(1,3)); // ["b","a"] console.log(arr.slice(1
,10)); // ["b","a"] console.log(arr); // ["p","b","a"] //sort() console.log(arr.sort()); // ["a","b","p"] console.log(arr); // ["a","b","p"] //splice() //it's going to modify the original array instead of just returning a new array arr.push("g"); arr.push("w"); console.log(arr); // ["a","b","p","g","w"] console.log(arr.splice(2,2,"JS Nuggets")); // ["p","g"] console.log(arr); // ["a","b","JS Nuggets","w"]