10 common Array methods in JS

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/stanxl/article/details/80957576
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"]


猜你喜欢

转载自blog.csdn.net/stanxl/article/details/80957576
今日推荐