Javascript 關於array的使用

Javascript 關於array的使用

來自: https://luoyangfu.com/detail/...前端

最近作項目常常會使用到數組,尤爲在一箇中臺系統中,數組是尤其常見的,並且前端數組能夠實現任何有序數據結構,總結一下數組的方方面面。git

使用

建立數組

const arr = [] // 直接申明
const arr1 = new Array() // 使用示例構建
const arr2 = Array()
const arr3 = Array.of(1, 2) // 從多個參數直接構建一個Array
const arr4 = Array.from(likeArr) // 從一個類數組中建立一個數組

上面能夠使用Array.from 進行數組深複製。關於深複製詳見其餘博文github

方法

數組簡單用法

array 方法的callback 參數

https://cdn-cos.luoyangfu.com/2018-07-31/image/15325043380339.jpg
翻譯說: 傳入一個回調函數callback, callback 裏面有三個參數當前遍歷的元素element, 當前元素的座標index, 以及遍歷的數組array. 還有一個可選參數,在find裏面使用this就是這個值thisArg若是未傳入,則是根據當前執行環境獲取this。
https://cdn-cos.luoyangfu.com/2018-07-31/image/15325042271600.jpgexpress

Array.prototype.find

用法

const a = [1, 2, 4]
const value = a.find(current => current > 3)
console.log(value) // 4

參數

https://cdn-cos.luoyangfu.com/2018-07-31/image/15325035638048.jpg
參數看callback參數,返回結果數組中的符合條件的值,若是是對象則返回對象引用。數組

返回一個array中的值,若是是對象或者數組則返回引用,直接修改會改動數組中的值

Array.prototype.forEach

遍歷這個數組,可是在forEach中不能夠使用break、continue繼續中斷後續循環, 若是使用return 後將再也不執行return後的語句,也不影響forEach的循環以下圖:
https://cdn-cos.luoyangfu.com/2018-07-31/image/15330042006479.jpg數據結構

Array.prototype.slice

複製數組,能夠繼續數組淺拷貝(深拷貝和淺拷貝關注後續)
https://cdn-cos.luoyangfu.com/2018-07-31/image/15330044115975.jpg
slice 會複製最外層,類似的好比
https://cdn-cos.luoyangfu.com/2018-07-31/image/15330044610275.jpg
使用對象展開符號...app

slice 傳入兩個可選參數beginend,返回一個新的數組。以下:
https://cdn-cos.luoyangfu.com/2018-07-31/image/15330046082073.jpgdom

返回一個新數組能夠進行數組的鏈式操做

Array.prototype.concat

鏈接一個數組或者多個值:
https://cdn-cos.luoyangfu.com/2018-07-31/image/15330046890361.jpg函數

鏈接一個數組:
https://cdn-cos.luoyangfu.com/2018-07-31/image/15330047107823.jpgui

返回一個新數組,能夠進行數組的鏈式操做

Array.prototype.from

經過已存在數組進行淺拷貝或者一個類數組的對象轉化成數組:

https://cdn-cos.luoyangfu.com/2018-07-31/image/15330050367692.jpg

類數組轉化:
最明顯的類數組,例如查詢頁面dom:
https://cdn-cos.luoyangfu.com/2018-07-31/image/15330051352402.jpg
如今是NodeList,轉化成數組:
https://cdn-cos.luoyangfu.com/2018-07-31/image/15330051848437.jpg
https://cdn-cos.luoyangfu.com/2018-07-31/image/15330052155838.jpg
這樣就能夠使用全部的數組操做

返回的是數組就能夠鏈式使用方法了

Array.prototype.push

將一個值推入到數組的尾端,並返回新的數組長度。

https://cdn-cos.luoyangfu.com/2018-07-31/image/15330053355591.jpg

Array.prototype.pop

將一個值從數組的尾端移除,並返回移除數組中的那個值.

https://cdn-cos.luoyangfu.com/2018-07-31/image/15330054053272.jpg

pop 是 push 的反操做。使用push和pop能夠實現棧數據結構(先進後出)

Array.prototype.shift

將一個數據從數組的頭部移除。並返回移除的值
https://cdn-cos.luoyangfu.com/2018-07-31/image/15330056510776.jpg

Array.prototype.unshift

講一個數據添加到數組的頭部,並返回新數組的長度
https://cdn-cos.luoyangfu.com/2018-07-31/image/15330057202238.jpg

使用shift和unshift 能夠實現隊列的數據結構(先進先出)

Array.prototype.indexOf

獲取數組中某個值的座標,只能是字面量變量數組,不適用多維數組和多對象數組
https://cdn-cos.luoyangfu.com/2018-07-31/image/15330058971533.jpg

有一個可選參數fromIndex,從fromIndex但是搜索
https://cdn-cos.luoyangfu.com/2018-07-31/image/15330059853278.jpg

數組進階操做

Array.prototype.map

傳入一個回調函數,會對數組每一個參數執行callback:
https://cdn-cos.luoyangfu.com/2018-07-31/image/15330061357686.jpg
https://cdn-cos.luoyangfu.com/2018-07-31/image/15330061775475.jpg

polyfill(mdn)
// Production steps of ECMA-262, Edition 5, 15.4.4.19
// Reference: http://es5.github.io/#x15.4.4.19
if (!Array.prototype.map) {

  Array.prototype.map = function(callback/*, thisArg*/) {

    var T, A, k;

    if (this == null) {
      throw new TypeError('this is null or not defined');
    }

    // 1. Let O be the result of calling ToObject passing the |this| 
    //    value as the argument.
    var O = Object(this);

    // 2. Let lenValue be the result of calling the Get internal 
    //    method of O with the argument "length".
    // 3. Let len be ToUint32(lenValue).
    var len = O.length >>> 0;

    // 4. If IsCallable(callback) is false, throw a TypeError exception.
    // See: http://es5.github.com/#x9.11
    if (typeof callback !== 'function') {
      throw new TypeError(callback + ' is not a function');
    }

    // 5. If thisArg was supplied, let T be thisArg; else let T be undefined.
    if (arguments.length > 1) {
      T = arguments[1];
    }

    // 6. Let A be a new array created as if by the expression new Array(len) 
    //    where Array is the standard built-in constructor with that name and 
    //    len is the value of len.
    A = new Array(len);

    // 7. Let k be 0
    k = 0;

    // 8. Repeat, while k < len
    while (k < len) {

      var kValue, mappedValue;

      // a. Let Pk be ToString(k).
      //   This is implicit for LHS operands of the in operator
      // b. Let kPresent be the result of calling the HasProperty internal 
      //    method of O with argument Pk.
      //   This step can be combined with c
      // c. If kPresent is true, then
      if (k in O) {

        // i. Let kValue be the result of calling the Get internal 
        //    method of O with argument Pk.
        kValue = O[k];

        // ii. Let mappedValue be the result of calling the Call internal 
        //     method of callback with T as the this value and argument 
        //     list containing kValue, k, and O.
        mappedValue = callback.call(T, kValue, k, O);

        // iii. Call the DefineOwnProperty internal method of A with arguments
        // Pk, Property Descriptor
        // { Value: mappedValue,
        //   Writable: true,
        //   Enumerable: true,
        //   Configurable: true },
        // and false.

        // In browsers that support Object.defineProperty, use the following:
        // Object.defineProperty(A, k, {
        //   value: mappedValue,
        //   writable: true,
        //   enumerable: true,
        //   configurable: true
        // });

        // For best browser support, use the following:
        A[k] = mappedValue;
      }
      // d. Increase k by 1.
      k++;
    }

    // 9. return A
    return A;
  };
}

Array.prototype.reduce

須要兩個參數,一個callback參數,一個累加初始值.
callback參數:
https://cdn-cos.luoyangfu.com/2018-07-31/image/15330062611158.jpg
callback參數有三個累加的值acc, 當前值cv, 當前座標cvIdx, 當前數組arr

用法:
https://cdn-cos.luoyangfu.com/2018-07-31/image/15330064144458.jpg
求和:
https://cdn-cos.luoyangfu.com/2018-07-31/image/15330064662218.jpg
返回值根據初始化的值來變化,多是數組,對象,數字,字符串等等。

polyfill(mdn)
// Production steps of ECMA-262, Edition 5, 15.4.4.21
// Reference: http://es5.github.io/#x15.4.4.21
// https://tc39.github.io/ecma262/#sec-array.prototype.reduce
if (!Array.prototype.reduce) {
  Object.defineProperty(Array.prototype, 'reduce', {
    value: function(callback /*, initialValue*/) {
      if (this === null) {
        throw new TypeError( 'Array.prototype.reduce ' + 
          'called on null or undefined' );
      }
      if (typeof callback !== 'function') {
        throw new TypeError( callback +
          ' is not a function');
      }

      // 1. Let O be ? ToObject(this value).
      var o = Object(this);

      // 2. Let len be ? ToLength(? Get(O, "length")).
      var len = o.length >>> 0; 

      // Steps 3, 4, 5, 6, 7      
      var k = 0; 
      var value;

      if (arguments.length >= 2) {
        value = arguments[1];
      } else {
        while (k < len && !(k in o)) {
          k++; 
        }

        // 3. If len is 0 and initialValue is not present,
        //    throw a TypeError exception.
        if (k >= len) {
          throw new TypeError( 'Reduce of empty array ' +
            'with no initial value' );
        }
        value = o[k++];
      }

      // 8. Repeat, while k < len
      while (k < len) {
        // a. Let Pk be ! ToString(k).
        // b. Let kPresent be ? HasProperty(O, Pk).
        // c. If kPresent is true, then
        //    i.  Let kValue be ? Get(O, Pk).
        //    ii. Let accumulator be ? Call(
        //          callbackfn, undefined,
        //          « accumulator, kValue, k, O »).
        if (k in o) {
          value = callback(value, o[k], k, o);
        }

        // d. Increase k by 1.      
        k++;
      }

      // 9. Return accumulator.
      return value;
    }
  });
}

Array.prototype.fill

對數組繼續填充,傳入三個變量, 填充值value, 填充開始位置start, 填充結束位置end
https://cdn-cos.luoyangfu.com/2018-07-31/image/15330066583515.jpg

返回修改後的數組能夠繼續操做

polyfill(來自mdn)
if (!Array.prototype.fill) {
  Object.defineProperty(Array.prototype, 'fill', {
    value: function(value) {

      // Steps 1-2.
      if (this == null) {
        throw new TypeError('this is null or not defined');
      }

      var O = Object(this);

      // Steps 3-5.
      var len = O.length >>> 0;

      // Steps 6-7.
      var start = arguments[1];
      var relativeStart = start >> 0;

      // Step 8.
      var k = relativeStart < 0 ?
        Math.max(len + relativeStart, 0) :
        Math.min(relativeStart, len);

      // Steps 9-10.
      var end = arguments[2];
      var relativeEnd = end === undefined ?
        len : end >> 0;

      // Step 11.
      var final = relativeEnd < 0 ?
        Math.max(len + relativeEnd, 0) :
        Math.min(relativeEnd, len);

      // Step 12.
      while (k < final) {
        O[k] = value;
        k++;
      }

      // Step 13.
      return O;
    }
  });
}

Array.prototype.some

判斷是否存在知足回調函數返回的條件,回調函數條件如上callback 參數,返回值是true/false
https://cdn-cos.luoyangfu.com/2018-07-31/image/15330186460037.jpg

polyfill(mdn)
if (!Array.prototype.some) {
  Array.prototype.some = function(fun/*, thisArg*/) {
    'use strict';

    if (this == null) {
      throw new TypeError('Array.prototype.some called on null or undefined');
    }

    if (typeof fun !== 'function') {
      throw new TypeError();
    }

    var t = Object(this);
    var len = t.length >>> 0;

    var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
    for (var i = 0; i < len; i++) {
      if (i in t && fun.call(thisArg, t[i], i, t)) {
        return true;
      }
    }

    return false;
  };
}

Array.prototype.every

判斷數組中每個是否知足回調函數知足的條件,返回true/false
https://cdn-cos.luoyangfu.com/2018-07-31/image/15330187195714.jpg

polyfill(mdn)
if (!Array.prototype.every) {
  Array.prototype.every = function(callbackfn, thisArg) {
    'use strict';
    var T, k;

    if (this == null) {
      throw new TypeError('this is null or not defined');
    }

    // 1. Let O be the result of calling ToObject passing the this 
    //    value as the argument.
    var O = Object(this);

    // 2. Let lenValue be the result of calling the Get internal method
    //    of O with the argument "length".
    // 3. Let len be ToUint32(lenValue).
    var len = O.length >>> 0;

    // 4. If IsCallable(callbackfn) is false, throw a TypeError exception.
    if (typeof callbackfn !== 'function') {
      throw new TypeError();
    }

    // 5. If thisArg was supplied, let T be thisArg; else let T be undefined.
    if (arguments.length > 1) {
      T = thisArg;
    }

    // 6. Let k be 0.
    k = 0;

    // 7. Repeat, while k < len
    while (k < len) {

      var kValue;

      // a. Let Pk be ToString(k).
      //   This is implicit for LHS operands of the in operator
      // b. Let kPresent be the result of calling the HasProperty internal 
      //    method of O with argument Pk.
      //   This step can be combined with c
      // c. If kPresent is true, then
      if (k in O) {

        // i. Let kValue be the result of calling the Get internal method
        //    of O with argument Pk.
        kValue = O[k];

        // ii. Let testResult be the result of calling the Call internal method
        //     of callbackfn with T as the this value and argument list 
        //     containing kValue, k, and O.
        var testResult = callbackfn.call(T, kValue, k, O);

        // iii. If ToBoolean(testResult) is false, return false.
        if (!testResult) {
          return false;
        }
      }
      k++;
    }
    return true;
  };
}

Array.prototype.filter

過濾知足回調函數返回值的的數組,返回值是一個數組,若是沒有知足的則是空數組:

https://cdn-cos.luoyangfu.com/2018-07-31/image/15330189178746.jpg

polyfill(mdn)
if (!Array.prototype.filter) {
  Array.prototype.filter = function(fun/*, thisArg*/) {
    'use strict';

    if (this === void 0 || this === null) {
      throw new TypeError();
    }

    var t = Object(this);
    var len = t.length >>> 0;
    if (typeof fun !== 'function') {
      throw new TypeError();
    }

    var res = [];
    var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
    for (var i = 0; i < len; i++) {
      if (i in t) {
        var val = t[i];

        // NOTE: Technically this should Object.defineProperty at
        //       the next index, as push can be affected by
        //       properties on Object.prototype and Array.prototype.
        //       But that method's new, and collisions should be
        //       rare, so use the more-compatible alternative.
        if (fun.call(thisArg, val, i, t)) {
          res.push(val);
        }
      }
    }

    return res;
  };
}

Array.prototype.includes

數組中是否包含某個值:
https://cdn-cos.luoyangfu.com/2018-07-31/image/15330190816670.jpg

polyfill(mdn)
// https://tc39.github.io/ecma262/#sec-array.prototype.includes
if (!Array.prototype.includes) {
  Object.defineProperty(Array.prototype, 'includes', {
    value: function(searchElement, fromIndex) {

      // 1. Let O be ? ToObject(this value).
      if (this == null) {
        throw new TypeError('"this" is null or not defined');
      }

      var o = Object(this);

      // 2. Let len be ? ToLength(? Get(O, "length")).
      var len = o.length >>> 0;

      // 3. If len is 0, return false.
      if (len === 0) {
        return false;
      }

      // 4. Let n be ? ToInteger(fromIndex).
      //    (If fromIndex is undefined, this step produces the value 0.)
      var n = fromIndex | 0;

      // 5. If n ≥ 0, then
      //  a. Let k be n.
      // 6. Else n < 0,
      //  a. Let k be len + n.
      //  b. If k < 0, let k be 0.
      var k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);

      function sameValueZero(x, y) {
        return x === y || (typeof x === 'number' && typeof y === 'number' && isNaN(x) && isNaN(y));
      }

      // 7. Repeat, while k < len
      while (k < len) {
        // a. Let elementK be the result of ? Get(O, ! ToString(k)).
        // b. If SameValueZero(searchElement, elementK) is true, return true.
        // c. Increase k by 1. 
        if (sameValueZero(o[k], searchElement)) {
          return true;
        }
        k++;
      }

      // 8. Return false
      return false;
    }
  });
}

Array.prototype.sort

根據回調函數進行排序,參數:
https://cdn-cos.luoyangfu.com/2018-07-31/image/15330191401466.jpg

當什麼都不傳遞的時候,則根據每一個字符的Unicode的值
https://cdn-cos.luoyangfu.com/2018-07-31/image/15330193635910.jpg
傳入一個比較函數的時候:
https://cdn-cos.luoyangfu.com/2018-07-31/image/15330194437768.jpg

這裏描述幾種狀況:

  • 若是函數返回小於0,排序前一個值a放到一個小的下標
  • 若是函數返回返回0,則a和b的位置不變
  • 返回值大於0,則排序的後一個值b放到小的下標
  • 比較函數老是要返回類似的值,不同的值致使返回的結果未必是預料的。

https://cdn-cos.luoyangfu.com/2018-07-31/image/15330199336117.jpg

Array.prototype.reverse

數組的反轉,直接數組頭尾交換:
https://cdn-cos.luoyangfu.com/2018-07-31/image/15330200232839.jpg
更換後數組,和變換前數組是同一個對象,同sort函數。

Array.of

傳入多個變量,將其轉換成新的數組:
https://cdn-cos.luoyangfu.com/2018-07-31/image/15330201127922.jpg

一些數組變換操做

使用map

map 能夠會數組中每一個值進行相同函數操做,例如:
將一個變量中全部id取出來

var persons = [ { id: 3 }, { id: 4 }]
const ids = persons.map(p => p.id)

使用reduce

鏈式操做

所謂鏈式操做,就是直接返回數組直接繼續使用數組中方法,不熟悉不推薦使用,代碼維護性降低
以下:

const idsStr = persons.map(p => p.id).join(',') // 3,4(join返回字符串,能夠繼續使用字符串方法)

數組關於Promise的sao操做

看以下代碼:

Promise.all(ids.map(id => requestPersonById(id)).then(persons => {
    // persons 就是每一個id請求的人
})

數組和Set的故事

去重操做:

const arr = [...new Set(duplicateArr)]

https://cdn-cos.luoyangfu.com/2018-07-31/image/15330206415630.jpg

相關文章
相關標籤/搜索