Explain the JavaScript built-in object Array (array)
1. Two ways to create an array
Method one: array literal
var arr=[1,2,3,4,5,6];
Method 2: new Array()
var arr1=new Array(); //创建一个空数组
var arr2=new Array(2); //创建一个长度为2的数组
var arr3=new Array(2,3,4); //创建一个[2,3,4]的数组
Two. Two methods to detect whether it is an array
Method one: instanceof operator
var arr4=[1,2,3,4,5];
console.log(arr4 instanceof Array); //true
var arr5={};
console.log(arr5 instanceof Array); //false
Method 2: Array.isArray (parameter)
console.log(Array.isArray(arr4)); //true
console.log(Array.isArray(arr5)); //false
Three. Add and delete the method of array elements
- push() (add one or more elements to the end of the original array, the return value is the length of the new array)
- unshift() (add one or more elements at the beginning of the original array, the return value is the length of the new array)
- pop() (delete the last element of the original array, the return value is the deleted element)
- shift() (delete the first element of the original array, the return value is the deleted element)
var arr6=[1,2,3,4,5];
console.log(arr6.push(6,7)); //7
console.log(arr6.unshift(-1,0)); //9
var arr7=[1,2,3,4,5,6,7];
console.log(arr7.pop()); //7
var arr8=[3,4,5,6,7,8,9];
console.log(arr8.shift()); //3
Four. Array index method
- indexOf() (only the index of the first element is satisfied, if no element is found, -1 is returned)
- lastIndexOf() (search from back to front, return -1 if not found)
var arr12=['red','blue','yellow','green','pink','yellow'];
console.log(arr12.indexOf('pink')); //4
console.log(arr12.lastIndexOf('yellow')); //5