reverse() 進(jìn)行反轉(zhuǎn)數(shù)組
var value = [1,2,3,4,5]
value.reverse()
console.log(value) //[5,4,3,2,1]
shift()取得數(shù)組的第一項(xiàng)
unshift()在數(shù)組前面添加任意項(xiàng)
var colors = ["green", "blue", "yellow"]
colors.unshift("aaa", "aa")
console.log(colors) //["aaa", "aa", "green", "blue", "yellow"]
sort() 默認(rèn)按升序進(jìn)行排序,最小值放在前面,按照toString()轉(zhuǎn)型方法來比較
var values = [0,1,5,10,15]
values.sort()
console.log(values) // [0,1,10,15,5]
splice() 這個方法會改變原來的數(shù)組
替換、刪除、插入都可以操作
刪除第一項(xiàng)
var colors = ['red', 'green', 'blue']
var removed = colors.splice(0, 1) //
console.log(colors) // ['green', 'blue']
console.log(removed) // ['red']
從位置1插入兩項(xiàng)
var colors = ['red', 'green', 'blue']
var inserted = colors.splice(1, 0, 'orange','pink')
console.log(inserted) //[] 空數(shù)組
console.log(colors) //["red", "orange", "pink", "green", "blue"]
插入兩項(xiàng),刪除一項(xiàng)
var colors = ['red', 'green', 'blue']
var x = colors.splice(1, 1, 'orange', 'blue')
console.log(colors) //["red", "orange", "blue", "blue"]
console.log(x) //["green"]
ES5新增方法
every()
參數(shù)是一個函數(shù),每一項(xiàng)去執(zhí)行,如果都是true,則返回true
filter()
傳入一個函數(shù),每一項(xiàng)去執(zhí)行,對于返回true的項(xiàng)聚在一起,返回一個數(shù)組
var num = [1,2,3,4,5,6,7,8]
var fil = num.filter(function(item) {
return (item > 2)
})
console.log(fil) //[3, 4, 5, 6, 7, 8]
forEach()
數(shù)組中每一項(xiàng)運(yùn)行里面的參數(shù),沒有返回值
map()
每一項(xiàng)都去運(yùn)行里面的函數(shù),把所有返回的結(jié)果組成一個數(shù)組
some()
每一項(xiàng)運(yùn)行里面的函數(shù),如果其中有一個返回true,則最后的結(jié)果是true
reduce() reduceRight()
都用來遍歷數(shù)組所有的項(xiàng),特點(diǎn)是:
reduce() 從數(shù)組的第一項(xiàng)開始,reduceRight() 從數(shù)組的最后一項(xiàng)開始
接受的函數(shù)有4個參數(shù),前一個值,當(dāng)前值, 索引和數(shù)組對象
var values = [1, 2, 3, 4, 5]
var sum = values.reduce(function(prev, cur, index, array) {
return prev+cur
})
console.log(sum) //15
// reduceRight()也是同理的