<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

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

          共 1041字,需瀏覽 3分鐘

           ·

          2021-02-01 23:48

          來源 |?http://www.fly63.com/article/detial/9098


          在JavaScript中,創(chuàng)建數(shù)組可以使用數(shù)組構(gòu)造函數(shù),或者使用多個直接量[],有時是首選方法。數(shù)組對象繼承自O(shè)bject.prototype,對操作符返回的數(shù)組類型返回對象而不是array。
          然而,[]實(shí)例,數(shù)組也返回true。變量,類數(shù)組對象的實(shí)現(xiàn)更復(fù)雜,例如字符串對象,參數(shù)對象,參數(shù)對象不是數(shù)組的實(shí)例,但有長度屬性,并能通過索引取值,所以能像多個相同進(jìn)行循環(huán)操作。
          在這里,我將復(fù)習(xí)一些復(fù)制原型的方法,并探索這些方法的用法。

          循環(huán):.forEach

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

          .forEach有一個單獨(dú)的函數(shù)作為參數(shù),遍歷時間表時,每個數(shù)組元素均會調(diào)用它,從而函數(shù)接受三個參數(shù):

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

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

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

          此外,可以傳遞可選的第二個參數(shù),作為每次函數(shù)調(diào)用的一部分(此)。

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

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

          判斷:.some和.every

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

          如果找到目標(biāo)元素,一些立即返回true,否則一些返回false。某些函數(shù)只對已經(jīng)指定值的排序索引執(zhí)行;它不正極已刪除的或未指定值的元素調(diào)用。
          max = -Infinitysatisfied = [10, 12, 10, 8, 5, 23].some(function (value, index, array) {    if (value > max) max = value    return value < 10})console.log(max)// <- 12satisfied// <- true

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

          區(qū)分.join和.concat

          .join和.concat經(jīng)常替換。.join(separator)以separator作為分隔符分割的數(shù)組元素,并返回串聯(lián)形式,如果沒有提供分隔符,將使用替換的,.. concat會創(chuàng)建一個新副本,作為源數(shù)組的淺拷貝。

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

          • .concat返回一個新副本

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

          淺拷貝意味著新的副本和原始副本保持相同的對象引用,這通常是好事。例如:

          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

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

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

          .pop方法是.push的反操作,它返回被刪除的副本末尾元素。如果數(shù)組為空,將返回void 0(未定義),使用.pop和.push可以創(chuàng)建LIFO(后進(jìn)先出)棧。

          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創(chuàng)建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()// <- 1Using .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

          。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。調(diào)用。

          Array.prototype.map和上面提到的.forEach,.some和.every有相同的參數(shù)格式:.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非常地解釋了.map不會對已刪除的或未指定值的元素調(diào)用,但仍然會被包含在結(jié)果數(shù)組中。.map在創(chuàng)建或更改排序時非常有用,看下面的示例:

          // 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)    }})

          查詢:.filter

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

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

          [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)

          例如,“ 80”排在“ 9”之前,而不是在其后。

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

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

          • a和b補(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

          這兩個函數(shù)比較難理解,.reduce會從左往右遍歷數(shù)組,而.reduce右從從右往左遍歷數(shù)組,各自的用法:.reduce(回調(diào)(previousValue,currentValue,index,array),initialValue) 。

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

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

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

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

          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'

          復(fù)制:.slice

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

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

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

          function format (text, bold) {    if (bold) {        text = '' + text + ''    }    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')

          強(qiáng)大的.splice

          .splice是我最喜歡的原生數(shù)組函數(shù),只需要調(diào)用一次,就可以讓你刪除元素,插入新的元素,并能同時進(jìn)行刪除,插入操作。需要注意的是,.`concat和.slice,這個函數(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]

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

          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]

          發(fā)現(xiàn):.indexOf

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

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

          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。

          操作符:in

          在面試中新手容易犯的錯誤是重復(fù).indexOf和in操作符:

          var a = [1, 2, 5]1 in a// <- true, but because of the 2!5 in a// <- false

          當(dāng)然,這在性能上比.indexOf快復(fù)雜。

          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會修改尺寸本身。

          本文完?

          瀏覽 29
          點(diǎn)贊
          評論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報
          評論
          圖片
          表情
          推薦
          點(diǎn)贊
          評論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  色94色欧美 | AV日韩在线播放 | 日韩三级高清视频 | 豆花无码视频一区二区三区四区 | 国产日产久久高清欧美 |