JavaScript 開發必須掌握技能(二)- 更好的使用數組方法

来源:https://www.cnblogs.com/blmlove/archive/2020/04/12/12685828.html
-Advertisement-
Play Games

數組是用於儲存多個相同類型數據的集合,JavaScript 開發中數組開發是必須掌握技能,工作學習中沒少和數組打交道,所以重中之重必須掌握,以下是數組中常用方法及實例。 數組常用操作 1、創建數組 直接定義數組項方法; 構造函數new Array('Apple', 'Banana'); 定義一個空數 ...


數組是用於儲存多個相同類型數據的集合,JavaScript 開發中數組開發是必須掌握技能,工作學習中沒少和數組打交道,所以重中之重必須掌握,以下是數組中常用方法及實例。

數組常用操作

1、創建數組

  直接定義數組項方法;

  構造函數new Array('Apple', 'Banana');

  定義一個空數組,我們在push進想要的數組項。

const fruits = ['Apple', 'Banana']
console.log(fruits);//[ 'Apple', 'Banana' ]
console.log(fruits.length);//3

2、訪問(索引到)數組項 通過下標定位到數組項,JavaScript數組的索引為零:數組的第一個元素在index 0,最後一個元素在index等於數組length屬性減去1。但是使用無效的索引號將返回undefined

console.log(fruits[0]) //Apple
console.log(fruits[fruits.length-1])//Banana

3、遍曆數組 Array.forEach(),遍曆數組的方法很多,我將在往後的隨筆中更新。

fruits.forEach(function(item, index, array) {
    console.log(item, index)
})
// Apple 0
// Banana 1

4、添加數組項

  1. 添加到數組的末尾 Array.push()
    fruits.push('Orange')
    console.log(fruits)//[ 'Apple', 'Banana', 'Orange' ]
  2. 添加到數組的前面 Array.unshift()
    fruits.unshift('Strawberry')
    console.log(fruits)//[ 'Strawberry', 'Apple', 'Banana', 'Orange' ]

5、移除數組項

  1. 移除數組末尾項 Array.pop()
    fruits.pop()
    console.log(fruits)//[ 'Strawberry', 'Apple', 'Banana' ]
  2. 移除數組首項 Array.shift()
    fruits.shift()
    console.log(fruits)//[ 'Apple', 'Banana' ]

6、找到數組項的索引 Array.indexOf()

fruits.push('Mango')
let pos = fruits.indexOf('Banana')
console.log(fruits)//[ 'Apple', 'Banana', 'Mango' ]
console.log(pos)//1

7、按索引的位置刪除數組項 Array.splice(pos,n)

//Array.splice(pos,n)//pos指定索引的開始位置,一直到數組的結尾,n定義要刪除的數組項數目
fruits.splice(pos, 1)
console.log(fruits)//[ 'Apple', 'Mango' ]

8、賦值數組 Array.slice()

fruits.slice()
console.log(fruits)//[ 'Apple', 'Mango' ]

9、數組的其他常用方法

  1. Array.reverse() 將數組反轉就位(第一個數組元素成為最後一個,最後一個數組元素成為第一個)
    const fruits = ['Apple', 'Banana','Mango']
    console.log(fruits)//[ 'Apple', 'Banana', 'Mango' ]
    fruits.reverse();
    console.log(fruits)//[ 'Mango', 'Banana', 'Apple' ]
  2. Array.sort() 方法對數組中的元素進行適當排序
    var numbers = [4, 2, 5, 1, 3];
    numbers.sort(function(a, b) {
        return a - b;
    });
    console.log(numbers);
    // [1, 2, 3, 4, 5]
  3. Arrzy.fill()方法將數組中的所有元素更改為靜態值,從開始索引(預設0)到結束索引(預設array.length)。它返回修改後的數組
    const array1 = [1, 2, 3, 4];
    
    // fill with 0 from position 2 until position 4
    console.log(array1.fill(0, 2, 4));
    // expected output: [1, 2, 0, 0]
    
    // fill with 5 from position 1
    console.log(array1.fill(5, 1));
    // expected output: [1, 5, 5, 5]
    
    console.log(array1.fill(6));
    // expected output: [6, 6, 6, 6]
  4.  Array.concat()  數組合併(返回一個新數組,該數組是與其他數組和/或值連接在一起的該數組) 
    const fruits = ['Apple', 'Banana','Mango']
    const array = ['Strawberry']
    console.log(fruits)//[ 'Apple', 'Banana', 'Mango' ]
    const newArray = fruits.concat(array);
    console.log(newArray)//[ 'Apple', 'Banana', 'Mango', 'Strawberry' ]
  5. Array.entries()方法返回一個新Array Iterator對象,該對象包含數組中每個索引的鍵/值對。
    var a = ['a', 'b', 'c'];
    var iterator = a.entries();
    
    for (let e of iterator) {
      console.log(e);
    }
    // [0, 'a']
    // [1, 'b']
    // [2, 'c'] 
  6. Array.find() 方法返回提供的數組中滿足條件的第一個元素的
    const array1 = [5, 12, 8, 130, 44];
    const found = array1.find(element => element > 10);
    
    console.log(found);//12
  7. Array.filter() 數組過濾  Array.filter 是一個十分有用的方法。它通過回調函數過濾原數組,並將過濾後的項作為新數組返回 )

    //過濾出數組項長度大於6的項
    const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
    function test(words) {
        return words.filter(word => word.length > 6);
    }
    console.log(test(words));//[ 'exuberant', 'destruction', 'present' ]
  8. Array.includes() 判斷數組中是否包含指定元素   返回值為布爾類型true或者false
    const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
    let limit = words.includes("limit")
    let order = words.includes("order")
    console.log(limit)//true
    console.log(order)//false
  9. Array.indexOf() 返回數組中元素等於指定元素的第一個(最小)索引,如果沒有則返回-1
    const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
    let present = words.indexOf("limit")
    let order = words.indexOf("order")
    console.log(present)//1
    console.log(order)//-1
  10. Array.join() 將數組的所有元素連接到字元串中,數組轉字元串。
    const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
    console.log(words.join(','))//spray,limit,elite,exuberant,destruction,present
  11. Array.lastIndexOf() 方法返回可以在數組中找到給定元素的最後一個索引;如果不存在,則返回-1,也可以用作去掉字元串最後一個(字元)逗號操作
    const animals = ['Dodo', 'Tiger', 'Penguin', 'Dodo'];
    console.log(animals.lastIndexOf('Dodo'));//3
    console.log(animals.lastIndexOf('Tiger'));//1
    console.log(animals.lastIndexOf('order'));//-1
    
    const comma = "Dodo,Tiger,Penguin,";
    console.log(comma.substring(0,comma.lastIndexOf(',')));//Dodo,Tiger,Penguin
  12. Array.slice() 數組截取 方法將數組的一部分的淺表副本返回到新的數組對象中,該對象選自beginto endend不包括),其中beginend表示該數組中各項的索引。原始數組將不會被修改
    const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
    console.log(animals.slice(2));//["camel", "duck", "elephant"]
    console.log(animals.slice(2, 4));//["camel", "duck"]
    console.log(animals.slice(1, 5));// ["bison", "camel", "duck", "elephant"]
  13. Array.toString() 方法返回一個表示指定數組及其元素的字元串。
    const array1 = [1, 2, 'a', '1a'];
    console.log(array1.toString());//1,2,a,1a
  14. Array.toLocaleString() 返回一個表示數組元素的字元串。元素使用其toLocaleString方法轉換為字元串,並且這些字元串由特定於語言環境的字元串分隔(例如,逗號“,”)
    const array1 = [1, 'a', new Date()];
    const localeString = array1.toLocaleString('en', {timeZone: "UTC"});
    
    console.log(localeString);//1,a,2020-4-12 4:49:17 PM
  15. Array.every() 方法測試數組中的所有元素是否通過提供的功能實現的測試。它返回一個布爾值。
    
    
    //判斷數組中是否所有的項的length都大於4 
    const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
    function test(words) {
    return words.every(word => word.length > 4);
    }
    console.log(test(words));
    // true
  16. Array.findIndex() 方法返回滿足條件的數組中第一個元素的索引。否則返回表明沒有元素通過測試。-1
    const array1 = [5, 12, 8, 130, 44];
    const isLargeNumber = (element) => element > 13;
    
    console.log(array1.findIndex(isLargeNumber));//3
  17. Array.keys() 方法返回一個新Array Iterator對象,該對象包含數組中每個索引的鍵
    const array1 = ['a', 'b', 'c'];
    const iterator = array1.keys();
    
    for (const key of iterator) {
        console.log(key);
    }
    //0
    //1
    //2
  18. Array.values() 方法返回一個新Array Iterator對象,該對象包含數組中每個索引的值。
    const array1 = ['a', 'b', 'c'];
    const iterator = array1.values();
    
    for (const value of iterator) {
      console.log(value);
    }
    //a
    //b
    //c
  19. Array.map() 方法創建一個新數組,其中填充了在調用數組中每個元素上調用提供的函數的結果
    const array1 = [1, 4, 9, 16];
    const map1 = array1.map(x => x * 2);
    
    console.log(map1);//[ 2, 8, 18, 32 ]
  20. Array.reduce() 方法在數組的每個元素上執行reducer函數(由您提供),從而產生單個輸出值。
    const array1 = [1, 2, 3, 4];
    const reducer = (accumulator, currentValue) => accumulator + currentValue;
    
    // 1 + 2 + 3 + 4
    console.log(array1.reduce(reducer));
    // expected output: 10
    
    // 5 + 1 + 2 + 3 + 4
    console.log(array1.reduce(reducer, 5));
    // expected output: 15
  21. Array. reduceRight()方法對一個累加器和數組的每個值(從右到左)應用一個函數,以將其減小為單個值。
    const array1 = [[0, 1], [2, 3], [4, 5]].reduceRight(
      (accumulator, currentValue) => accumulator.concat(currentValue)
    );
    
    console.log(array1);
    // expected output: Array [4, 5, 2, 3, 0, 1]
  22. Array.some() 方法測試數組中的至少一個元素是否通過了由提供的功能實現的測試。它返回一個布爾值。
    const array = [1, 2, 3, 4, 5];
    const even = (element) => element % 2 === 0;
    
    console.log(array.some(even));//true

     

10、總結

  以上就是本次全部內容,相信看完你會收穫頗多,使用起來也會更熟練,很多方法可能不會使用到,但是學無止境,建議去看看 MDN 文檔 以尋找更好的方法。

  下麵是記得一次查閱資料時,查到一個網友的總結,挺不錯的,感謝分享:

  數組方法可先選擇性使用

  1. 假設我們要判斷數組中是否包含指定元素時:我們可以使用Array.includes()和Array.indexOf()均可以達到效果,但是可以使用前者代替後者,因為前者返回的是布爾值。
  2. 假設我們要通過主鍵id獲取相應詳細信息時,那對於返回值只有一項的時候,我們可以使用Array.find()。儘管Array.filter()可以實現,但是有可能符合條件的有多個項,那麼程式不會停止還會繼續檢索所有符合的項。並返回一個新的數組,所以不建議大家使用。
  3. 如果我們判斷數組中是否包含某一項時我們可以用Array.find()和Array.some()都能實現,看你的需要吧,如果只是判斷是否存在,那some()返回布爾類型,建議使用some();
  4. 使用 Array.reduce 替代 Array.filter 與 Array.map 的組合,

    事實上說,Array.reduce 不太容易理解。然而,如果我們先使用 Array.filter 過濾原數組,之後(對結果)再調用 Array.map (以獲取一個新數組)。這看起似乎有點問題,是我們忽略了什麼嗎?

    這樣做的問題是:我們遍歷了兩次數組。第一次是過濾原數組以獲取一個長度稍短的新數組,第二次遍歷(譯者註:指 Array.map)是對 Array.filter 的返回的新數組進行加工,再次創造了一個新數組!為得到最終的結果,我們結合使用了兩個數組方法。每個方法都有它自己的回調函數,而且供 Array.map 使用的臨時數組是由 Array.filter提供的,(一般而言)該數組無法復用。

    為避免如此低效場景的出現,我的建議是使用 Array.reduce 。一樣的結果,更好的代碼!Array.reduce 允許你將過濾後切加工過的項放進累加器中。累加器可以是需要待遞增的數字、待填充的對象、 待拼接的字元串或數組等。

    在上面的例子中,我們使用了 Array.map,(但更)建議使用累加器為待拼接數組的 Array.reduce 。在下麵的例子中,根據變數 env 的值,我們會將它加進累加器中或保持累加器不變(即不作任何處理)。

    const characters = [
        { name: 'ironman', env: 'marvel' },
        { name: 'black_widow', env: 'marvel' },
        { name: 'wonder_woman', env: 'dc_comics' },
    ];
    
    console.log(
        characters
            .filter(character => character.env === 'marvel')
            .map(character => Object.assign({}, character, { alsoSeenIn: ['Avengers'] }))
    );
    // [
    //   { name: 'ironman', env: 'marvel', alsoSeenIn: ['Avengers'] },
    //   { name: 'black_widow', env: 'marvel', alsoSeenIn: ['Avengers'] }
    // ]
    
    console.log(
        characters
            .reduce((acc, character) => {
                return character.env === 'marvel'
                    ? acc.concat(Object.assign({}, character, { alsoSeenIn: ['Avengers'] }))
                    : acc;
            }, [])
    )
    // [
    //   { name: 'ironman', env: 'marvel', alsoSeenIn: ['Avengers'] },
    //   { name: 'black_widow', env: 'marvel', alsoSeenIn: ['Avengers'] }
    // ]

     

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...