1、检测数组
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、创建数组
var newArr = new Array(); // 创建数组 var newArr = new Array(3); // 创建数组并指定长度 var newArr = new Array(1,2,[3,4]); //创建数组并赋值
3、添加元素
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、删除元素
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、截取和合并元素
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、数组的拷贝
var newArr = ['A','B','C','D','E']; newArr.slice(0); //["A", "B", "C", "D", "E"] newArr.concat(); //["A", "B", "C", "D", "E"]
7、数组的排序
var newArr = ['A','C','B','D','M']; newArr.reverse(); //["M", "D", "B", "C", "A"] newArr.sort(); //"A", "B", "C", "D", "M"]
8、数组的字符串转换
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、数组查找
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
备注:自己查找资料整理,仅供参考,谢谢~~
以上是说明Js数组操作基本方法的详细内容。更多信息请关注PHP中文网其他相关文章!