在JavaScript中,能夠經過兩種方式建立數組,構造函數和數組直接量, 其中後者爲首選方法。數組對象繼承自Object.prototype,對數組執行typeof操做符返回‘object’而不是‘array’。然而執行[] instanceof Array返回true。此外,還有類數組對象是問題更復雜,如字符串對象,arguments對象。arguments對象不是Array的實例,但卻有個length屬性,而且值能經過索引獲取,因此能像數組同樣經過循環操做。javascript
在本文中,我將複習一些數組原型的方法,並探索這些方法的用法。java
若是你想測試上面的例子,您能夠複製並粘貼到您的瀏覽器的控制檯中。git
這是JavaScript原生數組方法中最簡單的方法。不用懷疑,IE7和IE8不支持此方法。github
forEach方法須要一個回調函數,數組內的每一個元素都會調用一次此方法,此方法須要三個參數以下:面試
此外,能夠傳遞可選的第二個參數,做爲每一個調用函數的上下文(this)。express
['_', 't', 'a', 'n', 'i', 'f', ']'].forEach(function (value, index, array) { this.push(String.fromCharCode(value.charCodeAt() + index + 2)) }, out = []) out.join('') // <- 'awesome'
.join函數我將在下文說起,上面例子中,它將數組中的不一樣元素拼接在一塊兒,相似於以下的效果:out[0] + '' + out[1] + '' + out[2] + '' + out[n]。數組
咱們不能用break中斷forEach循環,拋出異常是不明智的方法。幸運的是,咱們有其餘的方法中斷操做。瀏覽器
若是你曾經用過.NET的枚舉,這些方法的名字和.Any(x => x.IsAwesome)
和 .All(x => x.IsAwesome)很是類似。
app
這些方法和.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
注意,當回調函數的value < 10 條件知足時,中斷函數循環。.every的工做行爲相似,但回調函數要返回false而不是true。
.join方法常常和.concat混淆。.join(分隔符)方法建立一個字符串,會將數組裏面每一個元素用分隔符鏈接。若是沒有提供分隔符,默認的分隔符爲「,」。.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
每一個人都知道向數組添加元素用.push。但你知道一次能夠添加多個元素嗎?以下[].push('a', 'b', 'c', 'd', 'z')。
.pop方法和.push成對使用,它返回數組的末尾元素並將元素從數組移除。若是數組爲空,返回void 0(undefined)。使用.push和.pop咱們能輕易模擬出LIFO(後進先出或先進後出)棧。
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
相反,咱們能夠用.unshift
和 .shift模擬FIFO(先進先出)隊列。
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能很容易遍歷數組元素,並作一些操做。
list = [1,2,3,4,5,6,7,8,9,10] while (item = list.shift()) { console.log(item) } list // <- []
map
方法會給原數組中的每一個元素(必須有值)都調用一次callback
函數.callback
每次執行後的返回值組合起來造成一個新數組.callback
函數只會在有值的索引上被調用; 那些歷來沒被賦過值或者使用delete刪除的索引則不會被調用。——MDN
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不會在沒被賦過值或者使用delete刪除的索引上調用,但他們仍然被包含在結果數組中。map在遍歷或改變數組方面很是有用,以下所示:
// 遍歷 [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' // 一個映射新對象的通用模式 items.map(function (item) { return { id: item.id, name: computeName(item) } })
filter對每一個數組元素執行一次回調函數,並返回一個由回調函數返回true的元素 組成的新數組。回調函數只會對已經指定值的數組項調用。
用法例子:.filter(fn(value, index, array), thisArgument)。把它想象成.Where(x => x.IsAwesome) LINQ expression(若是你熟悉C#),或者SQL語句裏面的WHERE。考慮到.filter僅返回callback函數返回真值的值,下面是一些有趣的例子。沒有傳遞給回調函數測試的元素被簡單的跳過,不會包含進返回的新書組裏。
[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(比較函數)
若是未提供比較函數,元素會轉換爲字符串,並按字典許排列。例如,在字典序裏,「80」排在「9」以前,但實際上咱們但願的是80在9以後(數字排序)。
像大部分排序函數同樣,Array.prototype.sort(fn(a,b))須要一個包含兩個測試參數的回調函數,而且要產生一下三種返回值之一:
[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函數不是很好理解,.reduce從左到右而.reduceRight從右到左循環遍歷數組,每次調用接收目前爲止的部分結果和當前遍歷的值。
兩種方法都有以下典型用法:.reduce(callback(previousValue, currentValue, index, array), initialValue)。
previousValue是最後被調用的回調函數的返回值,initialValue是開始時previousValue被初始化的值。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
上面提到若是想把數組連成一個字符串,可使用.join。當數組的值是對象的狀況下,除非對象有能返回其合理值的valueof或toString方法,不然.join的表現和你指望的不同。然而,咱們可使用.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'
和.concat相似,調用.slice缺省參數時,返回原數組的淺拷貝。slice函數須要兩個參數,一個是開始位置和一個結束位置。
Array.prototype.slice能被用來將類數組對象轉換爲真正的數組。
Array.prototype.slice.call({ 0: 'a', 1: 'b', length: 2 }) // <- ['a', 'b']
除此以外,另外一個常見用途是從參數列表中移除最初的幾個元素,並將類數組對象轉換爲真正的數組。
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是我最喜歡的原生數組函數之一。它容許你刪除元素,插入新元素,或在同一位置同時進行上述操做,而只使用一個函數調用。注意和.concat和.slice不一樣的是.splice函數修改原數組。
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]
你可能已經注意到,它也返回被刪除的元素。若是你想遍歷已經刪除的數組時這可能會派上用場。
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,咱們能夠查找數組元素的位置。若是沒有匹配元素則返回-1。我發現我用的不少的一個模式是連續比較,例如a === 'a' || a === 'b' || a === 'c',或者即便只有兩個結果的比較。在這種狀況下,你也可使用.indexOf,像這樣:['a', 'b', 'c'].indexOf(a) !== -1。
注意這對指向同一個引用的對象一樣適用。第二個參數是開始查詢的起始位置。
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能派上用場。
在面試中新手容易犯的錯誤是混淆.indexOf和in操做符,以下:
var a = [1, 2, 5] 1 in a // <- true, 但由於 2! 5 in a // <- false
問題的關鍵是in操做符檢索對象的鍵而非值。固然,這在性能上比.indexOf快得多。
var a = [3, 7, 6] 1 in a === !!a[1] // <- true
in操做符相似於將鍵值轉換爲布爾值。!!表達式一般被開發者用來雙重取非一個值(轉化爲布爾值)。實際上至關於強制轉換爲布爾值,任何爲真的值被轉爲true,任何爲假的值被轉換爲false。
這方法將數組中的元素翻轉並替換原來的元素。
var a = [1, 1, 7, 8] a.reverse() // [8, 7, 1, 1]
和複製不一樣的是,數組自己被更改。在之後的文章中我將展開對這些概念的理解,去看看如何建立一個庫,如Underscore或Lo-Dash。
本文爲翻譯文章,原文爲「Fun with JavaScript Native Array Functions」。