数组的方法
1.join(分隔符) 将数组的值拼接成一个字符串
var arr=[15,89,65,69] console.log(arr.join('-')) //15-89-65-69
var arr=[15,89,65,69] console.log(arr.join('')) //15896569
var arr=[15,89,65,69] console.log(arr.join(' ')) //15 89 65 69
2.数组的增删操作
(1)push()后面添加一个或多个
var arr=['张三','李四','王五'] arr.push('田七') console.log(arr) //["张三", "李四", "王五", "田七"]
(2)pop()后面删除一个
var arr=['张三','李四','王五'] arr.pop() console.log(arr) //["张三", "李四"]
(3)unshift() 前面增加一个或者多个
var arr=['张三','李四','王五'] arr.unshift('赵六') console.log(arr) //["赵六", "张三", "李四", "王五"]
(4)shift() 前面删除一个
var arr=['张三','李四','王五'] arr.shift() console.log(arr) //["李四", "王五"]
3.数组的翻转与排序
(1)reverse() 翻转
var arr=[1,2,3,4,5,6] arr.reverse() console.log(arr) //[6, 5, 4, 3, 2, 1]
(2) sort() 排序,默认比较字符
var arr=['f','d','a','e','c','b'] arr.sort() console.log(arr) // ["a", "b", "c", "d", "e", "f"]
sort(function(a,b){a-b}) 数字排序 升序
var arr=[23,98,54,36,26,65] arr.sort(function(a,b){ return a-b }) console.log(arr) //[23, 26, 36, 54, 65, 98]
sort(function(a,b){b-a}) 数字排序 降序
var arr=[23,98,54,36,26,65] arr.sort(function(a,b){ return b-a }) console.log(arr) //[98, 65, 54, 36, 26, 23]
4.数组的拼接与截取
(1)arr1.concat(arr2) 两个数字拼接var arr1=[2,7,8] var arr2=[58,96] var arr3=arr1.concat(arr2) console.log(arr3) //[2, 7, 8, 58, 96]
(2)slice(start,end)截取出来 包括start 不包括end
var arr=[2,7,28,18,15] var arr1=arr.slice(1,3) console.log(arr1) //[7, 28]
slice(start)截取出来
var arr=[2,7,28,18,15] var arr1=arr.slice(1) console.log(arr1) //[7, 28, 18, 15]
(3)splice()删除或添加
splice(start,deleteCount)
var arr=[2,7,28,18,15] var arr1=arr.splice(2,2) console.log(arr) //[2, 7, 15]