一、创建数组的两种基本方式
1.使用Array构造函数
let colors = new Array();
let colors = new Array(20); //指定数组长度
let colors = new Array("red",1,true);//创建一个包含三个元素的数组
//new操作符也可以省略
2.使用数组字面量
let colors = ["red",1,true];
let colors = [];
二、常用方法
1.数组的栈方法
- push(newele1,newele2,newele3…) :把参数顺序添加到数组尾部,返回添加后数组的新长度
- unshift(newele1,newele2,newele3…) :把参数顺序添加到数组头部,返回添加后数组的新长度
- pop() :删除数组最后一个元素,返回被删除的那个元素
- shift() :删除数组第一个元素, 返回被删除的那个元素
2.数组转换方法
- join(separator):将数组中的所有元素放入一个字符串,返回该字符串。
括号内指定以什么方式分割字符串,什么都不写是默认逗号分割,“”空串表示不分割。
3.数组重排序方法
- reverse():将数组元素顺序颠倒,返回该数组。
- sort(sortby) :将数组元素排序,返回该数组。
1.即使数组中都是数值,比较的也是字符串
2.括号内可以写比较函数,这样就可以来对数字进行排序
按降序排列 sort(function(a,b){return b-a})
按升序排列 sort(function(a,b){return a-b})
4.数组操作方法
- concat(array1,array2,array3…):连接两个或多个数组,返回连接后的数组
- slice(start,[end]) :从数组中返回选定元素,返回该数组 start规定从何处选取,如果为负数,加上数组的长度
end可选,从何处结束,但是不能取到end;没有end,则从start取到结束
5.splice()
三大功能:删除,插入和替换,通过接收的参数来实现,返回含有被删除元素的数组
- 删除:splice(index,count) 从下表为index的位置删除count个元素 count设置要删除的元素数量,0则不删除;不设置则删除index后面所有元素
- 插入:splice(index,0,item1,item2…) 从下标为index的位置开始增加item1、item2等等
- 替换:splice(index,count,item1,item2…)从下标为index的位置删除count个元素,然后增加item1、item2等等
6.数组位置方法
返回查找的项在数组中的位置,没找到返回-1。
- indexOf(searchValue,[starrIndex]) :顺序在数组中查找
- lastIndexOf(searchValue,[starrIndex]) :倒序在数组中查找
searchValue和元素比较时使用全等,要求比较严格
总结
以上是常用方法,后续会继续更新