自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

有趣的JavaScript原生數(shù)組函數(shù)

開發(fā) 前端
在JavaScript中,創(chuàng)建數(shù)組可以使用Array構(gòu)造函數(shù),或者使用數(shù)組直接量[],后者是首選方法。Array對象繼承自O(shè)bject.prototype,對數(shù)組執(zhí)行typeof操作符返回object而不是array。然而,[] instanceof Array也返回true。

在JavaScript中,創(chuàng)建數(shù)組可以使用Array構(gòu)造函數(shù),或者使用數(shù)組直接量[],后者是***方法。Array對象繼承自O(shè)bject.prototype,對數(shù)組執(zhí)行typeof操作符返回object而不是array。然而,[] instanceof Array也返回true。也就是說,類數(shù)組對象的實(shí)現(xiàn)更復(fù)雜,例如strings對象、arguments對象,arguments對象不是Array的實(shí)例,但有l(wèi)ength屬性,并能通過索引取值,所以能像數(shù)組一樣進(jìn)行循環(huán)操作。
在本文中,我將復(fù)習(xí)一些數(shù)組原型的方法,并探索這些方法的用法。

  • 循環(huán):.forEach

  • 判斷:.some和.every

  • 區(qū)分.join和.concat

  • 棧和隊列的實(shí)現(xiàn):.pop, .push, .shift,和 .unshift

  • 模型映射:.map

  • 查詢:.filter

  • 排序:.sort

  • 計算:.reduce和.reduceRight

  • 復(fù)制:.slice

  • 強(qiáng)大的.splice

  • 查找:.indexOf

  • 操作符:in

  • 走近.reverse

循環(huán):.forEach

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

.forEach 有一個回調(diào)函數(shù)作為參數(shù),遍歷數(shù)組時,每個數(shù)組元素均會調(diào)用它,回調(diào)函數(shù)接受三個參數(shù):

  • value:當(dāng)前元素

  • index:當(dāng)前元素的索引

  • array:要遍歷的數(shù)組

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

  1. ['_''t''a''n''i''f'']'].forEach(function (value, index, array) { 
  2.     this.push(String.fromCharCode(value.charCodeAt() + index + 2)) 
  3. }, out = []) 
  4. out.join(''
  5. // <- 'awesome' 

后文會提及.join,在這個示例中,它用于拼接數(shù)組中的不同元素,效果類似于out[0] + ” + out[1] + ” + out[2] + ” + out[n]。

不能中斷.forEach循環(huán),并且拋出異常也是不明智的選擇。幸運(yùn)的事我們有另外的方式來中斷操作。

判斷:.some和.every

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

some將會給數(shù)組里的每一個元素執(zhí)行一遍回調(diào)函數(shù),直到回調(diào)函數(shù)返回true。如果找到目標(biāo)元素,some立即返回true,否則some返回false。回調(diào)函數(shù)只對已經(jīng)指定值的數(shù)組索引執(zhí)行;它不會對已刪除的或未指定值的元素調(diào)用。

  1. max = -Infinity 
  2. satisfied = [1012108523].some(function (value, index, array) { 
  3.     if (value > max) max = value 
  4.     return value < 10 
  5. }) 
  6. console.log(max) 
  7. // <- 12 
  8. satisfied 
  9. // <- true 

注意,當(dāng)回調(diào)函數(shù)的value < 10時,中斷函數(shù)循環(huán)。.every的運(yùn)行原理和.some類似,但回調(diào)函數(shù)是返回false而不是true。

區(qū)分.join和.concat

.join和.concat 經(jīng)?;煜?。.join(separator)以separator作為分隔符拼接數(shù)組元素,并返回字符串形式,如果沒有提供separator,將使用默認(rèn)的,。.concat會創(chuàng)建一個新數(shù)組,作為源數(shù)組的淺拷貝。

  • .concat常用用法:array.concat(val, val2, val3, valn)

  • .concat返回一個新數(shù)組

  • array.concat()在沒有參數(shù)的情況下,返回源數(shù)組的淺拷貝。

淺拷貝意味著新數(shù)組和原數(shù)組保持相同的對象引用,這通常是好事。例如:

  1. var a = { foo: 'bar' } 
  2. var b = [123, a] 
  3. var c = b.concat() 
  4. console.log(b === c) 
  5. // <- false 
  6. b[3] === a && c[3] === a 
  7. // <- true 

棧和隊列的實(shí)現(xiàn):.pop, .push, .shift和 .unshift

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

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

 

  1. function Stack () { 
  2.     this._stack = [] 
  3. Stack.prototype.next = function () { 
  4.     return this._stack.pop() 
  5. Stack.prototype.add = function () { 
  6.     return this._stack.push.apply(this._stack, arguments) 
  7. stack = new Stack() 
  8. stack.add(1,2,3
  9. stack.next() 
  10. // <- 3 
  11. 相反,可以使用.shift和 .unshift創(chuàng)建FIFO (first in first out)隊列。 
  12.  
  13. function Queue () { 
  14.     this._queue = [] 
  15. Queue.prototype.next = function () { 
  16.     return this._queue.shift() 
  17. Queue.prototype.add = function () { 
  18.     return this._queue.unshift.apply(this._queue, arguments) 
  19. queue = new Queue() 
  20. queue.add(1,2,3
  21. queue.next() 
  22. // <- 1 
  23. Using .shift (or .pop) is an easy way to loop through a set of array elements, while draining the array in the process. 
  24. list = [1,2,3,4,5,6,7,8,9,10
  25. while (item = list.shift()) { 
  26.     console.log(item) 
  27. list 
  28. // <- [] 

模型映射:.map

.map為數(shù)組中的每個元素提供了一個回調(diào)方法,并返回有調(diào)用結(jié)果構(gòu)成的新數(shù)組。回調(diào)函數(shù)只對已經(jīng)指定值的數(shù)組索引執(zhí)行;它不會對已刪除的或未指定值的元素調(diào)用。

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

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

undefined × 3很好地解釋了.map不會對已刪除的或未指定值的元素調(diào)用,但仍然會被包含在結(jié)果數(shù)組中。.map在創(chuàng)建或改變數(shù)組時非常有用,看下面的示例:

  1. // casting 
  2. [1'2''30''9'].map(function (value) { 
  3.     return parseInt(value, 10
  4. }) 
  5. // 1, 2, 30, 9 
  6. [97119101115111109101].map(String.fromCharCode).join(''
  7. // <- 'awesome' 
  8. // a commonly used pattern is mapping to new objects 
  9. items.map(function (item) { 
  10.     return { 
  11.         id: item.id, 
  12.         name: computeName(item) 
  13.     } 
  14. }) 

查詢:.filter

filter對每個數(shù)組元素執(zhí)行一次回調(diào)函數(shù),并返回一個由回調(diào)函數(shù)返回true的元素組成的新數(shù)組。回調(diào)函數(shù)只會對已經(jīng)指定值的數(shù)組項調(diào)用。

通常用法:.filter(fn(value, index, array), thisArgument),跟C#中的LINQ表達(dá)式和SQL中的where語句類似,.filter只返回在回調(diào)函數(shù)中返回true值的元素。

  1. [void 0nullfalse''1].filter(function (value) { 
  2.     return value 
  3. }) 
  4. // <- [1] 
  5. [void 0nullfalse''1].filter(function (value) { 
  6.     return !value 
  7. }) 
  8. // <- [void 0, null, false, ''] 

排序:.sort(compareFunction)

如果沒有提供compareFunction,元素會被轉(zhuǎn)換成字符串并按照字典排序。例如,”80″排在”9″之前,而不是在其后。

跟大多數(shù)排序函數(shù)類似,Array.prototype.sort(fn(a,b))需要一個包含兩個測試參數(shù)的回調(diào)函數(shù),其返回值如下:

  • a在b之前則返回值小于0

  • a和b相等則返回值是0

  • a在b之后則返回值小于0

  1. [9,80,3,10,5,6].sort() 
  2. // <- [10, 3, 5, 6, 80, 9] 
  3. [9,80,3,10,5,6].sort(function (a, b) { 
  4.     return a - b 
  5. }) 
  6. // <- [3, 5, 6, 9, 10, 80] 

計算:.reduce和.reduceRight

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

previousValue 是***一次調(diào)用回調(diào)函數(shù)的返回值,initialValue則是其初始值,currentValue是當(dāng)前元素值,index是當(dāng)前元素索引,array是調(diào)用.reduce的數(shù)組。

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

  1. Array.prototype.sum = function () { 
  2.     return this.reduce(function (partial, value) { 
  3.         return partial + value 
  4.     }, 0
  5. }; 
  6. [3,4,5,6,10].sum() 
  7. // <- 28 

如果想把數(shù)組拼接成一個字符串,可以用.join實(shí)現(xiàn)。然而,若數(shù)組值是對象,.join就不會按照我們的期望返回值了,除非對象有合理的valueOf或toString方法,在這種情況下,可以用.reduce實(shí)現(xiàn):

  1. function concat (input) { 
  2.     return input.reduce(function (partial, value) { 
  3.         if (partial) { 
  4.             partial += ', ' 
  5.         } 
  6.         return partial + value 
  7.     }, ''
  8. concat([ 
  9.     { name: 'George' }, 
  10.     { name: 'Sam' }, 
  11.     { name: 'Pear' } 
  12. ]) 
  13. // <- 'George, Sam, Pear' 

復(fù)制:.slice

和.concat類似,調(diào)用沒有參數(shù)的.slice()方法會返回源數(shù)組的一個淺拷貝。.slice有兩個參數(shù):一個是開始位置和一個結(jié)束位置。
Array.prototype.slice 能被用來將類數(shù)組對象轉(zhuǎn)換為真正的數(shù)組。

  1. Array.prototype.slice.call({ 0'a'1'b', length: 2 }) 
  2. // <- ['a', 'b'] 

這對.concat不適用,因?yàn)樗鼤脭?shù)組包裹類數(shù)組對象。

  1. Array.prototype.concat.call({ 0'a'1'b', length: 2 }) 
  2. // <- [{ 0: 'a', 1: 'b', length: 2 }] 

此外,.slice的另一個通常用法是從一個參數(shù)列表中刪除一些元素,這可以將類數(shù)組對象轉(zhuǎn)換為真正的數(shù)組。

  1. function format (text, bold) { 
  2.     if (bold) { 
  3.         text = '<b>' + text + '</b>' 
  4.     } 
  5.     var values = Array.prototype.slice.call(arguments, 2
  6.     values.forEach(function (value) { 
  7.         text = text.replace('%s', value) 
  8.     }) 
  9.     return text 
  10. format('some%sthing%s %s'true'some''other''things'

強(qiáng)大的.splice

.splice 是我最喜歡的原生數(shù)組函數(shù),只需要調(diào)用一次,就允許你刪除元素、插入新的元素,并能同時進(jìn)行刪除、插入操作。需要注意的是,不同于`.concat和.slice,這個函數(shù)會改變源數(shù)組。

  1. var source = [1,2,3,8,8,8,8,8,9,10,11,12,13
  2. var spliced = source.splice(344567
  3. console.log(source) 
  4. // <- [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ,13] 
  5. spliced 
  6. // <- [8, 8, 8, 8] 

正如你看到的,.splice會返回刪除的元素。如果你想遍歷已經(jīng)刪除的數(shù)組時,這會非常方便。

  1. var source = [1,2,3,8,8,8,8,8,9,10,11,12,13
  2. var spliced = source.splice(9
  3. spliced.forEach(function (value) { 
  4.     console.log('removed', value) 
  5. }) 
  6. // <- removed 10 
  7. // <- removed 11 
  8. // <- removed 12 
  9. // <- removed 13 
  10. console.log(source) 
  11. // <- [1, 2, 3, 8, 8, 8, 8, 8, 9] 

查找:.indexOf

利用.indexOf 可以在數(shù)組中查找一個元素的位置,沒有匹配元素則返回-1。我經(jīng)常使用.indexOf的情況是當(dāng)我有比較時,例如:a === ‘a’ || a === ‘b’ || a === ‘c’,或者只有兩個比較,此時,可以使用.indexOf:['a', 'b', 'c'].indexOf(a) !== -1。

注意,如果提供的引用相同,.indexOf也能查找對象。第二個可選參數(shù)用于指定開始查找的位置。

  1. var a = { foo: 'bar' } 
  2. var b = [a, 2
  3. console.log(b.indexOf(1)) 
  4. // <- -1 
  5. console.log(b.indexOf({ foo: 'bar' })) 
  6. // <- -1 
  7. console.log(b.indexOf(a)) 
  8. // <- 0 
  9. console.log(b.indexOf(a, 1)) 
  10. // <- -1 
  11. b.indexOf(21
  12. // <- 1 

如果你想從后向前搜索,可以使用.lastIndexOf。

操作符:in

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

  1. var a = [125
  2. 1 in a 
  3. // <- true, but because of the 2! 
  4. 5 in a 
  5. // <- false 

問題是in操作符是檢索對象的鍵而非值。當(dāng)然,這在性能上比.indexOf快得多。

  1. var a = [376
  2. 1 in a === !!a[1
  3. // <- true 

走近.reverse

該方法將數(shù)組中的元素倒置。

  1. var a = [1178
  2. a.reverse() 
  3. // [8, 7, 1, 1] 

.reverse 會修改數(shù)組本身。

參考

《Fun with JavaScript Native Array Functions》

責(zé)任編輯:張燕妮 來源: dwqs
相關(guān)推薦

2014-01-22 09:46:42

JavaScript數(shù)組

2023-03-13 08:47:06

CSS數(shù)學(xué)函數(shù)

2023-09-21 10:09:10

JavaScript數(shù)組分組

2022-03-30 09:01:37

CSS屬性函數(shù)

2012-05-29 21:22:32

蘋果

2021-04-05 14:48:51

JavaScriptjQuery函數(shù)

2020-03-29 20:27:51

Python函數(shù)開發(fā)

2021-02-05 08:18:29

JavaScript開發(fā)代碼

2011-07-11 10:16:07

JavaScript

2019-12-03 19:09:19

JavaScriptNumbers阿里云計算

2025-04-23 08:55:00

函數(shù)編程JavaScript

2017-05-08 14:35:14

JavascriptBOOM動畫效果

2023-08-13 16:32:12

JavaScript

2022-02-23 09:10:48

JavaScript標(biāo)簽?zāi)0?/a>前端

2016-12-05 15:15:52

JavaScriptCSS庫

2023-11-08 10:12:40

架構(gòu)函數(shù)元素

2023-04-17 16:21:20

JavaScriot前端開發(fā)

2014-12-01 09:54:40

JavaScript

2017-04-06 14:10:08

JavaScript數(shù)組排序

2019-07-17 14:06:45

JavaScript數(shù)組轉(zhuǎn)換
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號