簡體   English   中英

Javascript regex matchAll:為什么需要休息運算符?

[英]Javascript regex matchAll : why rest operator is needed?

在這個例子中https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/matchAll

為什么

const array = [...str.matchAll(regexp)];

而不僅僅是

const array = str.matchAll(regexp);

.matchAll返回一個迭代器 要從迭代器創建數組,將迭代器擴展到數組中是最簡潔的方法之一。

如果您需要一個數組,這適用於任何迭代器,而不僅僅是matchAll

但是,如果您只需要迭代迭代器,則不一定需要創建數組。 您還可以使用for..of進行迭代,而無需先轉換為數組,例如:

for (const match of str.matchAll(regexp)) {
  // do something with match
}

如果您不先將迭代器轉換為數組,並使用鏈接示例中的代碼,則記錄普通結果將不會提供很多信息:

 const regexp = /t(e)(st(\\d?))/g; const str = 'test1test2'; const iter = str.matchAll(regexp); console.log(iter);

在控制台中,您看到的只是一個沒有屬性的RegExpStringIterator對象。

如果你想知道為什么matchAll返回一個迭代器而不是一個數組,請看這里- 簡而言之,它允許在(有些不尋常的)情況下進行性能優化,在檢索所有可能的情況之前,人們可能希望避免對字符串進行迭代火柴。

您可以使用match而不是matchAll它返回數組:

let str = "abcd efgh";
let regex = /([a-z]+)/gi;
let arr = str.match(regex);

arr.forEach((el) => console.log(el));

輸出 :

abcd
efgh

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM