JavaScript總結之數組篇

Array數組篇

建立

構造函數

參數爲空則建立一個空數組;只有參數個數爲1而且該參數爲整數(參數可轉換爲整數)時,纔會建立一個長度爲當前參數值的空數組;不然參數將填充數組,充當數組內部元素。
console.log(new Array()); // []
console.log(new Array(3)); // [undefined, undefined, undefined]
console.log(new Array(Number(2))); // [undefined, undefined]
console.log(new Array('2')); // ["2"]
console.log(new Array([2])); // [[2]]
console.log(new Array({name:'rose'})); // [{name: "rose"}]
console.log(new Array(false)); // [false]
console.log(new Array(undefined)); // [undefined]
console.log(new Array(null)); // [null]
console.log(new Array(Symbol('bar'))) // [Symbol(bar)]
let attr = new Set([1,2,3,4]);
console.log(new Array(attr)); // [Set(4)]
attr = new Map([['name','jone'],['age',24]]);
console.log(new Array(attr)); // [Map(2)]
複製代碼

字面量(最經常使用的一種方式)

let attr = [];
console.log(attr); // []
attr = [2];
console.log(attr); // [2]
複製代碼

區別

字面量:我書寫簡單,而且你給我定義什麼我就輸出什麼,誰也管不着。javascript

構造函數:不懂我就別用我。java

屬性(2個屬性)

Length

  • 計算數組長度算法

  • const arr = [
       {
         name:'jone',
         address:'beijing',
       },
       {
         name:'rose',
         address:'hebei',
       },
     ];
    console.log(arr.length) // 輸出2
    複製代碼
  • 截斷數組,改變數組長度數組

  • const arr = [1,2,3,4,5];
    console.log(arr.length); // 5
    arr.length = 3;
    console.log(arr.length); // 3
    複製代碼
  • 範圍:0~2^32間整數bash

    • 查看數組最大長度框架

      • const attr = [];
        attr.length = Math.pow(2,32)-1; // 返回x的y次冪.
        console.log(attr.length); // 4294967295
        複製代碼
    • 不在長度範圍以內函數

      • const attr = [];
        attr.length = -123;
        console.log(attr.length); // error RangeError: Invalid array length
        attr.length = Math.pow() // Uncaught RangeError: Invalid array length
        複製代碼

prototype

  • ​ 對原型鏈稍微瞭解一點就能看懂ui

  • const attr = new Array(6);
    console.log(Object.getPrototypeOf(attr)); 
    console.log(attr.__proto__);
    console.log(Array.prototype);
    // 都輸出[constructor: ƒ, concat: ƒ, copyWithin: ƒ, fill: ƒ, find: ƒ, …]
    複製代碼

方法(34個方法)

檢測是否數組(1)

  • 不在一個全局環境下你能夠千萬別用我,例如多個iframe框架中穿梭,緣由:不在一個原型鏈,指向的內存地址不一樣。spa

    • instanceofprototype

      • const attr = new Array(6);
        console.log(attr instanceof Array); // true
        複製代碼
    • constructor()

      • const attr = new Array(6);
        console.log(attr.constructor === Array); // true
        複製代碼
  • 無論你在哪一個環境我都行。

    • Array.isArray()

      const attr = new Array(6);
      console.log(Array.isArray(attr)); // true
      複製代碼

轉換爲數組(2)

  • Array.from():一個相似數組可迭代對象中建立一個新的數組實例

    • 類數組對象

      // 注意:對象key必須是數字,不然轉換以後的數組元素都是undefined
      // 若是不指定length屬性,轉換後的數組長度將默認爲0
      let arrayLike = {
          '0': 'a',
          '1': 'b',
          '2': 'c',
          length: 3
      };
      console.log(Array.from(arrayLike))
      複製代碼

      還有一個經典例子,就是參數arguments,可自行嘗試

    • 可迭代對象

      何爲可迭代對象:只要具備Symbol.iterator屬性就是可迭代對象

      const s = 'hello word'; // 以字符串舉例,也可嘗試使用其餘的數據類型
      // 具備Symbol(Symbol.iterator): ƒ [Symbol.iterator]()
      console.log(Object.getPrototypeOf(s)); 
      console.log(Array.from(s)); // ["h", "e", "l", "l", "o", " ", "w", "o", "r", "d"]
      複製代碼
  • Array.of():建立一個具備可變數量參數的新數組實例,而不考慮參數的數量或類型;我的理解與字面量方式建立數組無區別,與構造函數方式相比,惟一區別在於只有一個參數,而且參數類型爲數字。

    • console.log(Array.of(3)); // [3]
      console.log(Array.of(1,2,3)); // [1,2,3]
      
      console.log(new Array(3)); // [undefined,undefined,undefined]
      console.log(new Array(1,2,3)); // [1,2,3]
      複製代碼

轉換爲字符串(3)

  • toString():返回數組中每一個值轉換爲string字符串以後拼接而成的新字符串

    • var array1 = [{name:'jone'}, 2, 'a', '1a'];
      
      console.log(array1.toString()); // "[object Object],2,a,1a"
      複製代碼
  • join():將一個數組(或一個類數組對象)的每一個元素調用toString方法的字符串拼接到一塊兒並返回這個字符串

    • const attr = [1,2,[3,4],'helo','word',{name:'age'}];
      console.log(attr.join('_')); // "1_2_3,4_helo_word_[object Object]"
      複製代碼
  • toLocaleString():與toString()方法相似,區別:這些字符串將使用一個特定語言環境的字符串

    • // 可選參數1:locales(一個 BCP 47 語言標記的字符串,或者是一個包括多個語言標記的數組。
      // 若是 locales 參數未提供或者是 undefined,便會使用運行時默認的 locale)。
      // 可選參數2:options():可自行研究
      var array1 = [1, 'a', new Date('21 Dec 1997 14:12:00 UTC')];
      console.log(array1.toLocaleString('zh-Hans-CN'));
      // "1,a,1997/12/21 下午10:12:00"
      console.log(array1.toLocaleString('en'));
      //"1,a,12/21/1997, 10:12:00 PM console.log(array1.toLocaleString('en', {timeZone: "UTC"})); // "1,a,12/21/1997, 2:12:00 PM" 複製代碼

棧方法(last-in-first-out)(2)

  • push(): 將一個或多個元素添加到數組的末尾,並返回該數組的新長度。(push好仍是value[]=''好呢?)

    • const attr = ['1',1,[1],{name:'jone'}];
      attr.push(2); // 添加一個
      attr.push(2,[3]);// 添加多個
      console.log(attr); // ["1", 1, [1], [object Object] {name: "jone"}, 2, 2, [3]]
      複製代碼
    • push和unshifti哪一個更好呢?(固然push,由於unshift每添加一個元素就須要吧全部元素向下移一位)

      • const s = 10000;
        const p=[];
        var begin=new Date();
        for(let i = 0;i<s;i++) {
          p.push(i);
        }
        var end=new Date();
        var time=end-begin;
        console.log("time is="+time); // "time is=7"
        
        
        var begins=new Date();
        for(let i = 0;i<s;i++) {
          p.unshift(i);
        }
        var ends=new Date();
        var times=ends-begins;
        console.log("time is="+times); // "time is=31"
        複製代碼
  • Pop():從數組中刪除最後一個元素,並返回該元素的值影響原來數組

    • const attr = [1,2,3,4];
      const s = attr.pop();
      console.log(attr); // [1, 2, 3]
      console.log(s); // 4
      複製代碼
    • pop仍是shift?(和樓上同理)

隊列方法(first-in-first-out)(2)

  • unshift():方法將一個或多個元素添加到數組的開頭,並返回該數組的新長度

    以塊的形式插入到數組的開始位置,順序和被做爲參數傳入時的順序一致。

    let arr = [4,5,6];
    arr.unshift(1,2,3);
    console.log(arr); // [1, 2, 3, 4, 5, 6]
    
    arr = [4,5,6];
    arr.unshift(1);
    arr.unshift(2);
    arr.unshift(3);
    console.log(arr); // [3, 2, 1, 4, 5, 6]
    複製代碼
  • shift():從數組中刪除第一個元素,並返回該元素的值影響原數組

    var array = [1, 2, 3];
    
    var firstElement = array.shift();
    
    console.log(array,firstElement); // [2,3] 1
    
    複製代碼

重排序方法(2)

  • sort():使用**原地算法(不開闢新的內存空間,操做原數組)**對數組的元素進行排序,並返回數組。

    • 無參數:元素會按照轉換爲的字符串的諸個字符的Unicode位點進行排序

    • // 我的理解都是獲取第一個字符的unicode碼而後進行排序。(有興趣的能夠看V8源碼)
      const obj = {};
      const months = ['Monday', 'Tuesday', 'Wednesday', 'Thursday','Friday','Saturday','Sunday'];
      months.forEach(val=>{
        obj[val] = val.toString().charCodeAt(0);
      })
      //{Monday: 77, Tuesday: 84, Wednesday: 87, Thursday: 84, Friday: 70, …}
      console.log(obj);
      // ["Friday", "Monday", "Saturday", "Sunday", "Thursday", "Tuesday", "Wednesday"]
      console.log(months.sort());
      
      const strObj = {};
      const str = ['文件','編輯','試圖','歷史記錄','書籤','用戶','窗口','幫助'];
      str.forEach(val=>{
        strObj[val] = val.toString().charCodeAt(0);
      })
      //{文件: 25991, 編輯: 32534, 試圖: 35797, 歷史記錄: 21382, 書籤: 20070, …}
      console.log(strObj);
      // ["書籤", "歷史記錄", "幫助", "文件", "用戶", "窗口", "編輯", "試圖"]
      console.log(str.sort());
      
      
      const num = [6,70.9,65,28,80,21,87];
      const numObj = {};
      num.forEach(val=>{
        numObj[val] = val.toString().charCodeAt(0);
      })
      //{6: 54, 21: 50, 28: 50, 65: 54, 80: 56, 87: 56, 70.9: 55}
      console.log(numObj);
      // [21, 28, 6, 65, 70.9, 80, 87]
      console.log(num.sort());
      複製代碼
      • 帶參數:參數形式爲函數,函數參數兩個值,分別表明第一個和第二個用於比較的值。

        規則:第一個參數以a表示,第二個參數以b表示。

        1. 返回值<0, a 會被排列到 b 以前
        2. 返回值>0,b 會被排列到 a 以前
        3. 返回值=0, a 和 b 的相對位置不變
        var items = [
          { name: 'Edward', value: 21 },
          { name: 'Sharpe', value: 37 },
          { name: 'And', value: 45 },
          { name: 'The', value: -12 },
          { name: 'Magnetic',value: 42 },
          { name: 'Zeros', value: 37 }
        ];
        
        // 根據value值比較
        items.sort(function (a, b) {
          return (a.value - b.value)
        });
        console.log(items);
        // 根據name的第一個字符比較
        items.sort(function(a, b) {
          var nameA = a.name.charCodeAt(0);
          var nameB = b.name.charCodeAt(0);
          if (nameA < nameB) {
            return -1;
          }
          if (nameA > nameB) {
            return 1;
          }
          return 0;
        });
        console.log(items);
        複製代碼
  • reverse():將數組中元素的位置顛倒,並返回該數組。影響原數組

    • var items = [
        { name: 'Edward', value: 21 },
        { name: 'Sharpe', value: 37 },
        { name: 'And', value: 45 },
        { name: 'The', value: -12 },
        { name: 'Magnetic',value: 42 },
        { name: 'Zeros', value: 37 }
      ];
      
      // 根據value值比較
      items.sort(function (a, b) {
        return (a.value - b.value)
      });
      console.log(items.reverse());
      // 根據name的第一個字符比較
      items.sort(function(a, b) {
        var nameA = a.name.charCodeAt(0);
        var nameB = b.name.charCodeAt(0);
        if (nameA < nameB) {
          return -1;
        }
        if (nameA > nameB) {
          return 1;
        }
        return 0;
      });
      console.log(items.reverse());
      複製代碼

位置方法(2)

  • indexOf(element[, fromIndex = 0]):返回在數組中能夠找到一個給定元素的第一個索引,若是不存在,則返回-1

    • const attr = ['hello','word'];
      console.log(attr.indexOf('hello'));
      複製代碼
  • lastIndexOf():與indexOf正好相反。

指定值查找(2)

  • find():參數是一個回調函數,全部數組成員執行該函數,直到找到第一個返回值爲true的成員,若是沒有返回undefined。參數當前元素、當前索引、源數組。

    • const s = [1,2,3,4];
      const sum = s.find((element,index,source)=>{
        return element>2;
      })
      console.log(sum); // 3
      複製代碼
  • findIndex():參數是一個回調函數,全部數組成員執行該函數,直到找到第一個返回值爲true的成員索引,若是沒有返回-1。參數當前元素、當前索引、源數組。

    • const s = [1,2,3,4];
      const sum = s.findIndex((element,index,source)=>{
        return element>2;
      })
      console.log(sum); // 2
      複製代碼

迭代方法(8)

  • every:對數組的每一項運行給定函數,若是該函數對每一項都返回true,則返回true.

    • const s = [1,2,3,4];
      const s1 = s.every((item)=>item>=2);
      console.log(s1);// 返回false
      複製代碼
  • some:對數組的每一項運行給定函數,只要任意一項知足條件就返回true.

    • const s = [1,2,3,4];
      const s1 = s.some((item)=>item>=2);
      console.log(s1); // true
      複製代碼
  • filter:對數組中的每一項執行函數,返回該函數會返回true的項組成的新數組

    • const s = [1,2,3,4];
      const s1 = s.filter((item)=>item>=2);
      console.log(s) // [1, 2, 3, 4]
      console.log(s1); // [2, 3, 4]
      複製代碼
  • forEach:對數組的每一項運行指定函數,沒有返回值,和for循環相似。

    • const s = [1,2,3,4];
      const s1 = s.forEach((item)=>item>=2);
      console.log(s1); // undefined
      複製代碼
  • map:對數組的每一項運行指定函數,返回指定函數返回值組成的新數組

    • const s = [1,2,3,4];
      const s1 = s.map((item)=>item+1);
      console.log(s1);//輸出[2,3,4,5]
      複製代碼
  • entries:返回一個包含數組中每一個索引的鍵/值對的Array Iterator對象。

    • const s = [1,2,3,4];
      console.log(s.entries());// Array Iterator {}
      for(let [key,values] of s.entries()){
        console.log(key+'..'+values);
      }
      複製代碼
  • keys:返回一個包含數組中每一個索引鍵的Array Iterator對象.

    • const s = [1,2,3,4];
      console.log(s.keys()); // Array Iterator {}
      for (let key of s.keys()) {
        console.log(key); // 0 1 2 3
      }
      複製代碼
  • values:返回一個包含數組中每一個索引值的Array Iterator對象.

    • const s = [1,2,3,4];
      console.log(s.values()); // Array Iterator {}
      for (let value of s.values()) {
        console.log(value); // 1 2 3 4
      }
      複製代碼

歸併方法(2)

  • reduce():從第一項開始,接收四個參數,累加值、當前值、當前索引、源數組,返回一個最終單個結果值

    • const s = [1,2,3,4];
      const sum = s.reduce((prev,cur,index,array)=>{
        console.log(prev+cur); // 3 6 10
        return prev+cur;
      })
      console.log(sum); // 10
      複製代碼
  • reduceRight():從最後一項開始,依次向前;接收四個參數,累加值、當前值、當前索引、源數組,返回一個最終單個結果值

    • const s = [1,2,3,4];
      const sum = s.reduceRight((prev,cur,index,array)=>{
        console.log(prev+cur); // 7 9 10
        return prev+cur;
      })
      console.log(sum); // 10
      複製代碼

數組填充(1)

  • fill():用一個固定值填充一個數組中從起始索引到終止索引內的所有元素,包頭不包尾。返回修改後的數組

    • const s = [1,2,3,4];
      s.fill('a',1,2);
      console.log(s); // [1, "a", 3, 4]
      s.fill('b');
      console.log(s); // ["b", "b", "b", "b"]
      複製代碼

拉平數組(2)

  • flat():參數爲指定深度遞歸的值,默認爲1,返回值爲一個包含將數組與子數組中全部元素的新數組。

    • const s = [1,2,3,4,[2,3,4],[[3,4,5]]];
      console.log(s.flat(1)); // [1, 2, 3, 4, 2, 3, 4, [3, 4, 5]]
      console.log(s.flat(2)); // [1, 2, 3, 4, 2, 3, 4, 3, 4, 5]
      複製代碼
  • FlatMap():對原數組的每一個成員執行一個函數(可理解爲map函數),而後對返回值組成的數組執行flat()方法。該方法返回一個新數組,不改變原數組.

    • const s = [1,2,3,4,5];
      
      const m = s.map((element,index,source)=>{
        return element*2;
      })
      console.log(m); // [2, 4, 6, 8, 10]
      const result = s.flatMap((element,index,source)=>{
        return [element*2];
      })
      console.log(result); // [2, 4, 6, 8, 10]
      複製代碼

包含某值(1)

  • includes():判斷一個數組是否包含一個指定的值,根據狀況,若是包含則返回 true,不然返回false。對象數組不能使用includes方法來檢測。

    const s = [1,2,3,4,5];
    
    console.log(s.includes(1)); // true
    複製代碼

數組合並(1)

  • concat():合併兩個或多個數組。此方法不會更改現有數組,而是返回一個新數組屬於淺拷貝

    • var array1 = ['a', 'b', 'c'];
      var array2 = ['d', 'e', ['g'],'f'];
      console.log(array1.concat(array2)); //["a", "b", "c", "d", "e", ["g"], "f"]
      複製代碼
  • (…):使用展開操做符。此方法不會更改現有數組,而是返回一個新數組屬於淺拷貝

    • var array1 = ['a', 'b', 'c'];
      var array2 = ['d', 'e', ['g'],'f'];
      
      console.log([...array1,...array2]); //["a", "b", "c", "d", "e", ["g"], "f"]
      複製代碼

截取方法(1)

  • ​ slice():截取數組,包頭不包尾,返回一個基於原數組淺拷貝的新數組,不影響原數組

    • const s = [1,2,3,4];
      const s1= s.slice(0,2);
      console.log(s); // [1,2,3,4]
      console.log(s1); // [1,2]
      複製代碼

替換現有值(2)

  • ​ copyWithin():淺複製數組的一部分到同一數組中的另外一個位置,並返回它,不會改變原數組的長度.

    參數

    • target

      0 爲基底的索引,複製序列到該位置。若是是負數,target 將從末尾開始計算。

      若是 target 大於等於 arr.length,將會不發生拷貝。若是 targetstart 以後,複製的序列將被修改以符合 arr.length

    • start

      0 爲基底的索引,開始複製元素的起始位置。若是是負數,start 將從末尾開始計算。

      若是 start 被忽略,copyWithin 將會從0開始複製。

    • end

      0 爲基底的索引,開始複製元素的結束位置。copyWithin 將會拷貝到該位置,但不包括 end 這個位置的元素。若是是負數, end 將從末尾開始計算。

      若是 end 被忽略,copyWithin 方法將會一直複製至數組結尾(默認爲 arr.length)。

    var array1 = ['a', 'b', 'c', 'd', 'e'];
    
    console.log(array1.copyWithin(0, 3, 4)); // ["d", "b", "c", "d", "e"]
    
    console.log(array1.copyWithin(1, 3)); // ["d", "d", "e", "d", "e"]
    複製代碼
  • splice():經過刪除或替換現有元素或者原地添加新的元素來修改數組,並以數組形式返回刪除的內容此方法會改變原數組。

    • // 刪除:傳遞兩個參數,第一個參數爲數組起始位置,第二個參數表明要刪除項的個數。
      var s = [1,2,3];
      console.log(s.splice(0,2));//[1, 2]
      console.log(s); // [3]
      
      // 插入:傳遞三個參數,第一個爲起始位置,第二個爲刪除的個數,第三個爲要插入的值,也能夠有第四個第五個參數。
      console.log(s.splice(1,0,3,4,56,7)); // []
      console.log(s); // [3, 3, 4, 56, 7]
      
      // 替換:傳遞三個參數,第一個爲起始位置,第二個爲刪除的個數,第三個爲要插入的值,也能夠有第四個第五個參數。
      console.log(s.splice(0,2,2,2)); // [3, 3]
      console.log(s); //[2, 2, 4, 56, 7]
      複製代碼
相關文章
相關標籤/搜索