1. Detect array
var newArr = [1,2,3]; newArr instanceof Array; // true Array.isArray(newArr) ; // true //Array.isArray(newArr) 只支持ie9+,firefox 4+,safari 5+,opera 10.5+和chrome
2. Create Array
var newArr = new Array(); // 创建数组 var newArr = new Array(3); // 创建数组并指定长度 var newArr = new Array(1,2,[3,4]); //创建数组并赋值
3, add element
var newArr = new Array(); // 创建数组 var newArr = new Array(3); // 创建数组并指定长度 var newArr = new Array(1,2,[3,4newArr.push('A'); //6 newArr; // [1,2,3,4,5,'A'] newArr.unshift('B'); //7 newArr; // ['B',1,2,3,4,5,'A'] newArr.splice(2,0,'C'); // [] newArr; //["B", 1, "C", 2, 3, 4, 5, "A"]]); //创建数组并赋值
4, delete element
var newArr = [1,2,3,4,5]; newArr.pop(); //5 newArr; // [1,2,3,4] newArr.shift(); //1 newArr; // [2,3,4] newArr.splice(1,2); //[3,4] newArr; //[2]
5, Intercepting and merging elements
var newArr = ['A','B','C','D','E']; newArr.slice(2); //["C", "D", "E"] newArr.slice(1,4); //["B", "C", "D"] newArr.concat('M'); //["A", "B", "C", "D", "E", "M"]
6. Copy of array
var newArr = ['A','B','C','D','E']; newArr.slice(0); //["A", "B", "C", "D", "E"] newArr.concat(); //["A", "B", "C", "D", "E"]
7. Array sorting
var newArr = ['A','C','B','D','M']; newArr.reverse(); //["M", "D", "B", "C", "A"] newArr.sort(); //"A", "B", "C", "D", "M"]
8. Array sortingStringConversion
var newArr = [1,2,3]; newArr.join(','); // "1,2,3" newArr.toString(); //"1,2,3" newArr.toLocaleString (); //"1,2,3" newArr.valueOf(); //[1,2,3] //toLocaleString 、toString 、valueOf:可以看作是join的特殊用法,不常用
9. Array search
var newArr = [1,2,3,4,5,4,3,2,3,4]; newArr.indexOf(3); // 第一次出现元素3的位置 :2 newArr.indexOf(3,4); //从位置3开始查找第一次出现元素4的位置:6 newArr.lastIndexOf(3); //最后一次出现元素3的位置:8 newArr.lastIndexOf(2,4); //从位置4开始查找最后一次出现元素2的位置:1 var person={name:"lili"}, person1=[{name:"lili"}], person2=[person]; person1.indexOf(person);//返回-1 必须严格相等,不仅仅是值相等 person2.indexOf(person);//返回0 // indexOf()从前往后查找,找不到为-1 // lastIndexOf()从后往前查找,找不到为-1
Note: Search and organize the information yourself, for reference only, thank you~~
The above is the detailed content of Explain the basic methods of Js array operation. For more information, please follow other related articles on the PHP Chinese website!