JavaScript原生數組函數使用例子

來源:互聯網
上載者:User


在JavaScript中,建立數組可以使用Array建構函式,或者使用數組直接量[],後者是首選方法。Array對象繼承自Object.prototype,對數組執行typeof操作符返回object而不是array。然而,[] instanceof Array也返回true。也就是說,類數組對象的實現更複雜,例如strings對象、arguments對象,arguments對象不是Array的執行個體,但有length屬性,並能通過索引取值,所以能像數組一樣進行迴圈操作。
在本文中,我將複習一些數組原型的方法,並探索這些方法的用法。

迴圈:.forEach
判斷:.some和.every
區分.join和.concat
棧和隊列的實現:.pop, .push, .shift,和 .unshift
模型映射:.map
查詢:.filter
排序:.sort
計算:.reduce和.reduceRight
複製:.slice
強大的.splice
尋找:.indexOf
操作符:in
走近.reverse
Array

迴圈:.forEach

這是JavaScript中最簡單的方法,但是IE7和IE8不支援此方法。

.forEach 有一個回呼函數作為參數,遍曆數組時,每個數組元素均會調用它,回呼函數接受三個參數:

value:當前元素

index:當前元素的索引

array:要遍曆的數組

此外,可以傳遞可選的第二個參數,作為每次函數調用的上下文(this).

['_', 't', 'a', 'n', 'i', 'f', ']'].forEach(function (value, index, array) {
    this.push(String.fromCharCode(value.charCodeAt() + index + 2))
}, out = [])
out.join('')
// <- 'awesome'
<div class="md-section-divider"></div>

後文會提及.join,在這個樣本中,它用於拼接數組中的不同元素,效果類似於out[0] + '' + out[1] + '' + out[2] + '' + out[n]。
不能中斷.forEach迴圈,並且拋出異常也是不明智的選擇。幸運的事我們有另外的方式來中斷操作。

判斷:.some和.every

如果你用過.NET中的枚舉,這兩個方法和.Any(x => x.IsAwesome) 、 .All(x => x.IsAwesome)類似。
和.forEach的參數類似,需要一個包含value,index,和array三個參數的回呼函數,並且也有一個可選的第二個上下文參數。MDN對.some的描述如下:

some將會給數組裡的每一個元素執行一遍回呼函數,直到回呼函數返回true。如果找到目標元素,some立即返回true,否則some返回false。回呼函數只對已經指定值的數組索引執行;它不會對已刪除的或未指定值的元素調用。
max = -Infinity
satisfied = [10, 12, 10, 8, 5, 23].some(function (value, index, array) {
    if (value > max) max = value
    return value < 10
})
console.log(max)
// <- 12
satisfied
// <- true
<div class="md-section-divider"></div>

注意,當回呼函數的value < 10時,中斷函數迴圈。.every的運行原理和.some類似,但回呼函數是返回false而不是true。

區分.join和.concat
.join和.concat 經常混淆。.join(separator)以separator作為分隔字元拼接數組元素,並返回字串形式,如果沒有提供separator,將使用預設的,。.concat會建立一個新數組,作為源數組的淺拷貝。

.concat常用用法:array.concat(val, val2, val3, valn)
.concat返回一個新數組
array.concat()在沒有參數的情況下,返回源數組的淺拷貝。
淺拷貝意味著新數組和原數組保持相同的對象引用,這通常是好事。例如:
var a = { foo: 'bar' }
var b = [1, 2, 3, a]
var c = b.concat()
console.log(b === c)
// <- false
b[3] === a && c[3] === a
// <- true
棧和隊列的實現:.pop, .push, .shift和 .unshift

每個人都知道.push可以再數組末尾添加元素,但是你知道可以使用[].push('a', 'b', 'c', 'd', 'z')一次性添加多個元素嗎?

.pop 方法是.push 的反操作,它返回被刪除的數組末尾元素。如果數組為空白,將返回void 0 (undefined),使用.pop和.push可以建立LIFO (last in first out)棧。

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

相反,可以使用.shift和 .unshift建立FIFO (first in first out)隊列。

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
Using .shift (or .pop) is an easy way to loop through a set of array elements, while draining the array in the process.
list = [1,2,3,4,5,6,7,8,9,10]
while (item = list.shift()) {
    console.log(item)
}
list
// <- []

模型映射:.map

.map為數組中的每個元素提供了一個回調方法,並返回有調用結果構成的新數組。回呼函數只對已經指定值的數組索引執行;它不會對已刪除的或未指定值的元素調用。

Array.prototype.map 和上面提到的.forEach、.some和 .every有相同的參數格式:.map(fn(value, index, array), thisArgument)

values = [void 0, null, false, '']
values[7] = void 0
result = values.map(function(value, index, array){
    console.log(value)
    return value
})
// <- [undefined, null, false, '', undefined × 3, undefined]

undefined × 3很好地解釋了.map不會對已刪除的或未指定值的元素調用,但仍然會被包含在結果數組中。.map在建立或改變數組時非常有用,看下面的樣本:

// 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 objects
items.map(function (item) {
    return {
        id: item.id,
        name: computeName(item)
    }
})

查詢:.filter

filter對每個數組元素執行一次回呼函數,並返回一個由回呼函數返回true的元素組成的新數組。回呼函數只會對已經指定值的數組項調用。
通常用法:.filter(fn(value, index, array), thisArgument),跟C#中的LINQ運算式和SQL中的where語句類似,.filter只返回在回呼函數中返回true值的元素。

[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, '']

排序:.sort(compareFunction)

如果沒有提供compareFunction,元素會被轉換成字串並按照字典排序。例如,”80″排在”9″之前,而不是在其後。

跟大多數排序函數類似,Array.prototype.sort(fn(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]

計算:.reduce和.reduceRight

這兩個函數比較難理解,.reduce會從左往右遍曆數組,而.reduceRight則從右往左遍曆數組,二者典型用法:.reduce(callback(previousValue,currentValue, index, array), initialValue)。

previousValue 是最後一次調用回呼函數的傳回值,initialValue則是其初始值,currentValue是當前元素值,index是當前元素索引,array是調用.reduce的數組。

一個典型的用例,使用.reduce的求和函數。

Array.prototype.sum = function () {
    return this.reduce(function (partial, value) {
        return partial + value
    }, 0)
};
[3,4,5,6,10].sum()
// <- 28
<div class="md-section-divider"></div>
如果想把數組拼接成一個字串,可以用.join實現。然而,若數組值是對象,.join就不會按照我們的期望傳回值了,除非對象有合理的valueOf或toString方法,在這種情況下,可以用.reduce實現:

function concat (input) {
    return input.reduce(function (partial, value) {
        if (partial) {
            partial += ', '
        }
        return partial + value
    }, '')
}
concat([
    { name: 'George' },
    { name: 'Sam' },
    { name: 'Pear' }
])
// <- 'George, Sam, Pear'
<div class="md-section-divider"></div>

複製:.slice

和.concat類似,調用沒有參數的.slice()方法會返回源數組的一個淺拷貝。.slice有兩個參數:一個是開始位置和一個結束位置。

Array.prototype.slice 能被用來將類數組對象轉換為真正的數組。

Array.prototype.slice.call({ 0: 'a', 1: 'b', length: 2 })
// <- ['a', 'b']
這對.concat不適用,因為它會用數組包裹類數組對象。

Array.prototype.concat.call({ 0: 'a', 1: 'b', length: 2 })
// <- [{ 0: 'a', 1: 'b', length: 2 }]
此外,.slice的另一個通常用法是從一個參數列表中刪除一些元素,這可以將類數組對象轉換為真正的數組。

function format (text, bold) {
    if (bold) {
        text = '<b>' + text + '</b>'
    }
    var values = Array.prototype.slice.call(arguments, 2)
    values.forEach(function (value) {
        text = text.replace('%s', value)
    })
    return text
}
format('some%sthing%s %s', true, 'some', 'other', 'things')
// <- <b>somesomethingother things</b>

強大的.splice

.splice 是我最喜歡的原生數組函數,只需要調用一次,就允許你刪除元素、插入新的元素,並能同時進行刪除、插入操作。需要注意的是,不同於`.concat和.slice,這個函數會改變源數組。

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]

正如你看到的,.splice會返回刪除的元素。如果你想遍曆已經刪除的數組時,這會非常方便。

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 13
console.log(source)
// <- [1, 2, 3, 8, 8, 8, 8, 8, 9]
尋找:.indexOf
利用.indexOf 可以在數組中尋找一個元素的位置,沒有匹配元素則返回-1。我經常使用.indexOf的情況是當我有比較時,例如:a === 'a' || a === 'b' || a === 'c',或者只有兩個比較,此時,可以使用.indexOf:['a', 'b', 'c'].indexOf(a) !== -1。
注意,如果提供的引用相同,.indexOf也能尋找對象。第二個選擇性參數用於指定開始尋找的位置。

var a = { foo: 'bar' }
var b = [a, 2]
console.log(b.indexOf(1))
// <- -1
console.log(b.indexOf({ foo: 'bar' }))
// <- -1
console.log(b.indexOf(a))
// <- 0
console.log(b.indexOf(a, 1))
// <- -1
b.indexOf(2, 1)
// <- 1
如果你想從後向前搜尋,可以使用.lastIndexOf。

操作符:in

在面試中新手容易犯的錯誤是混淆.indexOf和in操作符:

var a = [1, 2, 5]
1 in a
// <- true, but because of the 2!
5 in a
// <- false
問題是in操作符是檢索對象的鍵而非值。當然,這在效能上比.indexOf快得多。

var a = [3, 7, 6]
1 in a === !!a[1]
// <- true

走近.reverse
該方法將數組中的元素倒置。

var a = [1, 1, 7, 8]
a.reverse()
// [8, 7, 1, 1]
.reverse 會修改數組本身。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.