Array匯總

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)是:

  1. reduce() 從數(shù)組的第一項(xiàng)開始,reduceRight() 從數(shù)組的最后一項(xiàng)開始

  2. 接受的函數(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()也是同理的

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 第5章 引用類型(返回首頁) 本章內(nèi)容 使用對象 創(chuàng)建并操作數(shù)組 理解基本的JavaScript類型 使用基本類型...
    大學(xué)一百閱讀 3,679評論 0 4
  • ??引用類型的值(對象)是引用類型的一個實(shí)例。 ??在 ECMAscript 中,引用類型是一種數(shù)據(jù)結(jié)構(gòu),用于將數(shù)...
    霜天曉閱讀 1,219評論 0 1
  • 本章內(nèi)容 使用對象 創(chuàng)建并操作數(shù)組 理解基本的 JavaScript 類型 使用基本類型和基本包裝類型 引用類型的...
    悶油瓶小張閱讀 781評論 0 0
  • 創(chuàng)建與讀取 Array構(gòu)造函數(shù)創(chuàng)建 可以直接定義數(shù)組數(shù)量,例如,下面代碼將創(chuàng)建length值為20的數(shù)字。 或者向...
    DHFE閱讀 389評論 0 0
  • 數(shù)組是值的有序集合。每個值叫做一個元素,而每個元素在數(shù)組中有一個位置,以數(shù)字表示,稱為索引。 JavaScript...
    劼哥stone閱讀 1,251評論 6 20

友情鏈接更多精彩內(nèi)容