JavaScript中原生Array數(shù)組方法詳解

來源 |?http://www.fly63.com/article/detial/9692
循環(huán).forEach
斷言.some,.every
連接與合并.join,.concat
.pop,.push,.shift,.unshift
模型映射.map
過濾.filter
排序.sort
聚合.reduce,.reduceRight
截取.slice
刪除插入.splice
發(fā)現(xiàn)值.indexOf
在操作符中發(fā)現(xiàn)鍵
顛倒.reverse
1.forEach()
值當(dāng)前值 index當(dāng)前位置,索引值 array當(dāng)前數(shù)組
['_', 't', 'a', 'n', 'i', 'f', ']'].forEach(function (value, index, array) {this.push(String.fromCharCode(value.charCodeAt() + index + 2))}, out = [])out.join('')// <- 'awesome
forEach的缺陷是既不能中斷循環(huán),也不能引發(fā)異常。
2.some(),every()
這兩個(gè)方法類似“斷言”(assert),返回一個(gè)布爾值,表示判斷數(shù)組成員是否符合
某種條件。對(duì)于foreach,同樣接受一個(gè)包含值,索引和數(shù)組的變量函數(shù)作為參數(shù),而且也可以指定上下文中的這一點(diǎn)。
有些方法是只要一個(gè)成員的返回值是真,則整個(gè)某些方法的返回值就是真實(shí)的,否則返回假。
每個(gè)方法是所有成員的返回值都是真實(shí)的,整個(gè)每一個(gè)方法才返回真,否則返回false。
max = -Infinitysatisfied = [10, 12, 10, 8, 5, 23].some(function (value, index, array) {if (value > max) max = valuereturn value < 10})console.log(max)// <- 12satisfied// <- true
3.join()和concat()
這兩個(gè)方法容易搞混,加入是將多個(gè)內(nèi)部各個(gè)成員用分隔符連接成一個(gè)串聯(lián),分隔符交替是,, concat用于多個(gè)交錯(cuò)的合并。成員的后部,然后返回一個(gè)新副本,原副本不變。
var a = { foo: 'bar' }var b = [1, 2, 3, a]var c = b.concat()console.log(b === c)// <- falseb[3] === a && c[3] === a// <- true
4.pop,.push,.shift和.unshift
每個(gè)人都知道往上面的末尾添加一個(gè)元素是用push方法,但你知道可以一次性添加多個(gè)元素嗎,像這樣[] .push('a','b','c','d', 'z')。
pop是push方法的逆操作,移除了多個(gè)最后一個(gè)元素同時(shí)返回這個(gè)元素,如果是空分配則返回undefined,使用這兩個(gè)方法很容易實(shí)現(xiàn)LIFO(后進(jìn)先出)棧結(jié)構(gòu)。
function Stack () {this._stack = []}Stack.prototype.next = function () {return this._stack.pop()}Stack.prototype.add = function () {return this._stack.push.apply(this._stack, arguments)}stack = new Stack()stack.add(1,2,3)stack.next()// <- 3
相應(yīng)的,我們可以通過.unshift和.shift實(shí)現(xiàn)一個(gè)FIFO(先進(jìn)先出)類型。
function Queue () {this._queue = []}Queue.prototype.next = function () {return this._queue.shift()}Queue.prototype.add = function () {return this._queue.unshift.apply(this._queue, arguments)}queue = new Queue()queue.add(1,2,3)queue.next()// <- 1
使用.shift(或.pop)很容易用while循環(huán)清空一個(gè)數(shù)組,如下:
list = [1,2,3,4,5,6,7,8,9,10]while (item = list.shift()) {console.log(item)}list// <- []
5.map()
方法
簽名為forEach,.map(fn(value,index,array),thisArgument)。
values = [void 0, null, false, '']values[7] = void 0result = values.map(function(value, index, array){console.log(value)return value})// <- [undefined, null, false, '', undefined × 3, undefined]
undefined×3表明在某種程度上函數(shù)不會(huì)在已刪除或未賦值的成員執(zhí)行,而是自己返回包含在返回?cái)?shù)組中。地圖在映射或轉(zhuǎn)換排列時(shí)非常有用,下面有個(gè)例子:
// casting[1, '2', '30', '9'].map(function (value) {return parseInt(value, 10)})// 1, 2, 30, 9[97, 119, 101, 115, 111, 109, 101].map(String.fromCharCode).join('')// <- 'awesome'// a commonly used pattern is mapping to new objectsitems.map(function (item) {return {id: item.id,name: computeName(item)}})
6.filter()
filter方法用于過濾數(shù)組成員,滿足條件的成員組成一個(gè)新副本返回。
正在使用,.filter(fn(value,index,array),thisArgument)。
[void 0, null, false, '', 1].filter(function (value) {return value})// <- [1][void 0, null, false, '', 1].filter(function (value) {return !value})// <- [void 0, null, false, '']
7.sort(compareFunction)
排序方法對(duì)數(shù)組成員進(jìn)行排序,默認(rèn)是按照字典順序排序。排序后,原數(shù)組將被改變。
像大多數(shù)的排序函數(shù)一樣,Array.prototype.sort(FN(A,B))接受一個(gè)回調(diào)函數(shù)用于比較a,b的大小,而且為以下三種情況之一:
如果a在b之前,則返回值<0
如果a和b都等效,則返回值=== 0
如果a在b之后,則返回值> 0
[9,80,3,10,5,6].sort()// <- [10, 3, 5, 6, 80, 9][9,80,3,10,5,6].sort(function (a, b) {return a - b})// <- [3, 5, 6, 9, 10, 80]
8.reduce(),reduceRight()
Reduce函數(shù)一開始很難理解,這些函數(shù)會(huì)循環(huán)數(shù)組,從左向右(.reduce)或從右向左(.reduceRight),每次函數(shù)執(zhí)行時(shí)會(huì)接受之前的部分結(jié)果,最終返回值是單一聚合的值。
兩個(gè)方法具有相同的語(yǔ)法:
reduce(callback(previousValue, currentValue, index, array), initialValue)Array.prototype.sum = function () {return this.reduce(function (partial, value) {return partial + value}, 0)};[3,4,5,6,10].sum()// <- 28
9.slice()
slice()方法用于提取目標(biāo)片段的一部分,返回一個(gè)新副本,原先的位置不變。
arr.slice(start, end)它的第一個(gè)參數(shù)為起始位置(從0開始,會(huì)包括在返回的新細(xì)分之中),第二個(gè)參數(shù)為終止位置(但該位置的元素本身不包括內(nèi)部)。如果省略第二一個(gè)參數(shù),則一直返回到原始副本的最后一個(gè)成員。
與concat()類似,slice()如果沒有任何參數(shù)則返回原始數(shù)組的淺表副本。Array.prototype.slice可以用作將類的對(duì)象轉(zhuǎn)換成真正的數(shù)組。
Array.prototype.slice.call({ 0: 'a', 1: 'b', length: 2 })// <- ['a', 'b']
concat做不到,它會(huì)返回一個(gè)包含目標(biāo)對(duì)象的層疊。
Array.prototype.concat.call({ 0: 'a', 1: 'b', length: 2 })// <- [{ 0: 'a', 1: 'b', length: 2 }]
10.splice()
.splice是我最喜歡的數(shù)組原始數(shù)組方法,它允許您在一次性在同一個(gè)位置刪除,插入元素,注意:這個(gè)函數(shù)會(huì)改變?cè)瓟?shù)組。
var source = [1,2,3,8,8,8,8,8,9,10,11,12,13]var spliced = source.splice(3, 4, 4, 5, 6, 7)console.log(source)// <- [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ,13]spliced// <- [8, 8, 8, 8]
你可能注意到了,它會(huì)返回被刪除的元素,這個(gè)常用于循環(huán)被刪除的元素,你之前可能忘記了。
var source = [1,2,3,8,8,8,8,8,9,10,11,12,13]var spliced = source.splice(9)spliced.forEach(function (value) {console.log('removed', value)})// <- removed 10// <- removed 11// <- removed 12// <- removed 13console.log(source)// <- [1, 2, 3, 8, 8, 8, 8, 8, 9]
11.indexOf(),lastIndexOf()
indexOf方法返回給定元素在多個(gè)中第一次出現(xiàn)的位置,如果沒有出現(xiàn)則返回-1。
var a = { foo: 'bar' }var b = [a, 2]console.log(b.indexOf(1))// <- -1console.log(b.indexOf({ foo: 'bar' }))// <- -1console.log(b.indexOf(a))// <- 0console.log(b.indexOf(a, 1))// <- -1b.indexOf(2, 1)// <- 1
lastIndexOf方法返回給定元素在多個(gè)中最后一次出現(xiàn)的位置,如果沒有出現(xiàn)則返回-1。
注意,這兩個(gè)方法不能用來搜索NaN的位置,即無法確定該成員是否包含NaN。
這是因?yàn)檫@兩個(gè)方法內(nèi)部,使用嚴(yán)格的內(nèi)部運(yùn)算符(===)進(jìn)行比較,而NaN是唯一一個(gè)不等于自身的值。
12.在操作符中
在用于查找關(guān)鍵中,索引速度則是查找值。當(dāng)然速度快于indexOf。
var a = [1, 2, 5]1 in a// <- true, but because of the 2!5 in a// <- falsevar a = [3, 7, 6]1 in a === !!a[1]// <- true
在操作符跟把相應(yīng)位置的值轉(zhuǎn)換為布爾值類似。表達(dá)式常用于將一個(gè)值取反然后再取反,這是一種高效的將真值轉(zhuǎn)為布爾值的方式。
13.reverse()
注意,該方法將更改原始數(shù)組。
var a = ['a', 'b', 'c'];a.reverse() // ["c", "b", "a"]a // ["c", "b", "a"]

