JavaScript >> Javascript 文檔 >  >> JavaScript

了解 JavaScript 中的 Array.from() 方法

Array.from() JavaScript 中的方法創建一個新的、淺拷貝的 Array 實例 來自類似數組或可迭代的對象。您可以使用此方法來轉換類似數組的對象(帶有 length 的對象 屬性和索引項)以及可迭代對象(Map 和 Set 等對象)到數組中。

語法

這是 Array.from() 的語法 方法:

Array.from(arrayLikeOrIterable[, mapFunction[, thisArg]])
  • arrayLikeOrIterable — 要轉換為數組的類數組或可迭代對象。
  • mapFunction(item, index) {...} — 一個可選的 map 函數,用於調用集合中的每個元素。當您想同時將類數組或可迭代對象轉換和轉換為數組時,此方法非常有用。
  • thisArgthisArg 的值 用作 this 在調用 mapFunction 時 .

Array.from() 方法返回新的 Array 實例。當你通過 mapFunctionArray.from() ,它對新創建的數組的每個元素執行一個 map() 函數。

簡而言之,Array.from(obj, mapFunction, thisArg) 結果與 Array.from(obj).map(mapFunction, thisArg) 相同 , 只是它不創建中間數組。

來自 String 的數組

Array.from() 可用於在 JavaScript 中將字符串轉換為數組。字符串的每個字母都轉換為新數組實例的一個元素:

const str = 'Apple';

const arr = Array.from(str); // same as str.split('')

console.log(arr);

// ['A', 'p', 'p', 'l', 'e']

來自 Set 的數組

Set 是 ES6 中引入的一種特殊類型的對象,它允許我們創建唯一值的集合。轉換 Set 到一個唯一值的數組,你可以使用 Array.from() 方法:

const set = new Set(['🐦', '🦉', '🦆', '🦅']);

const birds = Array.from(set);

console.log(birds);

// ['🐦', '🦉', '🦆', '🦅']

您還可以使用上面的代碼從數組中刪除重複項:

function unique(arr) {
    return Array.from(new Set(arr));
};

unique([1, 2, 2, 3, 4, 4]);

// [1, 2, 3, 4]

來自 Map 的數組

Map 是另一種 ES6 數據結構,可讓您創建鍵值對的集合。這是一個轉換 Map 實例的示例 使用 Array.from() 到一個數組 方法:

const map = new Map([
    ['🍌', 'Banana'],
    ['🍕', 'Pizza'],
    ['🥒', 'Cucumber'],
    ['🌽', 'Maize'],
]);

const foods = Array.from(map);

console.log(foods);

// [['🍌', 'Banana'], ['🍕', 'Pizza'], ['🥒', 'Cucumber'], ['🌽', 'Maize']]

來自 NodeList 的數組

NodeList 是一個類似數組的對象,它包含一組 DOM 元素或更具體的節點。不轉換 NodeList 對像到數組,不能使用map()等常見的數組方法 , slice() , 和 filter() 就可以了。

轉換 NodeList 到一個數組,你可以使用 Array.from() 方法:

const divs = document.querySelectorAll('div');

const divsArr = Array.from(divs);

// now you can use array methods
divsArr.map(div => console.log(div.innerText));

查看這篇文章以了解有關 NodeList 的更多信息 到數組轉換。

來自 arguments 的數組

arguments object 是一個類數組對象,可在所有非箭頭函數中訪問,其中包含傳遞給該函數的參數值。

轉換 arguments 對像到一個真正的數組,你可以使用 Array.from() 方法:

function numbers() {
    const args = Array.from(arguments);

    console.log(args);
}

numbers(1, 2, 3, 4, 5);

// [1, 2, 3, 4, 5]

克隆數組

在之前的文章中,我們研究了幾種創建數組克隆的方法。其中之一是 Array.from() 創建現有數組的淺拷貝:

const fruits = ['🍑', '🍓', '🍉', '🍇'];

const moreFruits = Array.from(fruits);

console.log(moreFruits);

// ['🍑', '🍓', '🍉', '🍇']

要創建數組的深層克隆,請查看本指南。

初始化數組

Array.from() 當您想用相同的值或對像初始化數組時,該方法也很有幫助:

const length = 4;

// init array with 0
Array.from({ length }, () => 0);
// [0, 0, 0, 0]

// init array with random values
Array.from({ length }, () => Math.floor(Math.random() * 10) + 1);
// [2, 4, 2, 10]

// init array with objects
Array.from({ length }, () => ({}));

// [{}, {}, {}, {}]

生成一系列數字

您也可以使用 Array.from() JavaScript中生成數字序列的方法:

const range = (stop) => {
    return Array.from({ length: stop }, (item, index) => index);
}

range(5); // [0, 1, 2, 3, 5]

瀏覽器兼容性

Array.from() 是 ES6 的一部分,它只適用於現代瀏覽器。要支持 IE 等舊版瀏覽器,您可以使用 MDN 上提供的 polyfill。

要詳細了解 JavaScript 數組以及如何使用它們將多條信息存儲在一個變量中,請查看這篇文章。

閱讀下一篇: 了解 JavaScript 中的 Object.assign() 方法


Tutorial JavaScript 教程
  1. 不確定如何在更改導航選項卡時停止計時器重置

  2. 人們怎麼沒有意識到開發人員是有創造力的?!請允許我演示。

  3. 如何在 Node.js 的 console.log() 中獲取完整的對象,而不是 '[Object]'?

  4. CS 投資組合

  5. 類管理器 Django + React

  6. YNAPB(你需要一個個人博客),以及如何做到這一點

  7. JavaScript 中的 .trim() 在 IE 中不起作用

  1. 如何突出顯示和選擇多行?

  2. 如何使瀏覽器控制台日誌等到頁面重新加載後

  3. For 循環如何真正起作用

  4. 介紹 reactjs-popup 🎉 —  模式、工具提示和菜單 —  多合一

  5. 是 Storybook 的核心維護者,問我們任何問題!

  6. 使用 Docker 的容器中的 Node.js

  7. JavaScript 中的方法鍊是什麼,它是如何工作的以及如何使用它

  1. 從 Silverlight 調用 Javascript 函數

  2. 為靜態站點選擇 NGINX 而不是 Http-server 的 3 個原因

  3. 看看 DevDocs.io

  4. CSS 3D