常見的數(shù)組操作
數(shù)組操作一段時間不用就會不熟悉托酸,總結(jié)常用的操作斤蔓,持續(xù)更新中
instanceof 判斷是否是數(shù)組
let a = [1,2,3,4]
a instanceof Array // true
a instanceof Object // true
isArray 判斷是否是數(shù)組
let a = [1,2,3,4]
Array.isArray(a) // true
toString 轉(zhuǎn)成字符串
let a = [1,2,3,4]
a.toString() // "1,2,3,4"
join 轉(zhuǎn)成字符串
let a = [1,2,3,4]
a.join('') //"1234"
A.join("|")//"1|2|3|4"
數(shù)組的添加和刪除
push 和 pop
push 返回值為新數(shù)組的長度,pop的返回值為刪除掉的那個元素扼脐,2方法都會改變原數(shù)組
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:在數(shù)組最前面添加一個元素竿痰,返回數(shù)組長度
shift:移除第一個元素苟弛,返回移除的那一項(xiàng)
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
數(shù)組排序
reverse 數(shù)組翻轉(zhuǎn)
函數(shù)返回值為翻轉(zhuǎn)之后的數(shù)組
let a = [1,2,3,4]
let b = a.reverse() // a:[4,3,2,1] b:[4,3,2,1]
sort排序
默認(rèn)的排序?yàn)閡nicode排序
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
數(shù)組元素的操作
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]