常见的数组操作
数组操作一段时间不用就会不熟悉,总结常用的操作,持续更新中
instanceof 判断是否是数组
let a = [1,2,3,4]
a instanceof Array // true
a instanceof Object // true
isArray 判断是否是数组
let a = [1,2,3,4]
Array.isArray(a) // true
toString 转成字符串
let a = [1,2,3,4]
a.toString() // "1,2,3,4"
join 转成字符串
let a = [1,2,3,4]
a.join('') //"1234"
A.join("|")//"1|2|3|4"
数组的添加和删除
push 和 pop
push 返回值为新数组的长度,pop的返回值为删除掉的那个元素,2方法都会改变原数组
let a = [1,2,3,4]
let b = ['a','b','c','d']
let c = a.push(5) // a:[1,2,3,4,5] c:5
let d = b.pop() // b:['a','b','c'] d:'d'
unshift 和 shift
unshift:在数组最前面添加一个元素,返回数组长度
shift:移除第一个元素,返回移除的那一项
let a = [1,2,3,4]
let b = ['a','b','c','d']
let c = a.shift() // a:[2,3,4] c:1
let d = b.unshift('e') //b:['e','a','b','c','d'] d:1
数组排序
reverse 数组翻转
函数返回值为翻转之后的数组
let a = [1,2,3,4]
let b = a.reverse() // a:[4,3,2,1] b:[4,3,2,1]
sort排序
默认的排序为unicode排序
let a = [1,2,3,4,'a','b','c','d','1','2','3','4']
a.sort() // [1, "1", "2", 2, 3, "3", "4", 4, "a", "b", "c", "d"]
let b = [1,2,3,4]
let c = b.sort((next,prev)=>prev-next) //c:[4,3,2,1] b:[4,3,2,1]
b === c // true
数组元素的操作
concat
let a = [1,2,3]
let b = [4,5,6]
let c = a.concat(b) // c:[1,2,3,4,5,6] a:[1,2,3] b:[4,5,6]