簡體   English   中英

如何檢查內部的所有數組元素 endwith()

[英]How to Check All Array Element Inside endswith()

 let array1 = ["?", "!", "."]; let array2 = ["live.", "ali!", "harp", "sharp%", "armstrong","yep?"]; console.log(array2.filter((x) => x.endsWith("?")));

輸出只是: ['yep?']

因為函數endsWith()只檢查了"?" 正如您在代碼中看到的那樣。 如何在endsWith函數內循環array1 (后綴)上的元素,以便輸出為:

['live.', 'ali!', 'yep?']

您可以使用regex ,然后將filter迭代中的每個元素與之match

/[?!.]$/表示在字符串結束( $ )之前匹配組中的這些東西之一[?!.] )。

 const arr = ['live.', 'ali!', 'harp', 'sharp%', 'armstrong', 'yep?']; const re = /[?!.]$/; const out = arr.filter(el => el.match(re)); console.log(out);

關於您的評論,您可以使用模板字符串將連接數組傳遞給RegExp 構造函數

 const query = ['.', '?', '!']; const re = new RegExp(`[${query.join('')}]$`); const arr = ['live.', 'ali!', 'harp', 'sharp%', 'armstrong', 'yep?']; const out = arr.filter(el => el.match(re)); console.log(out);

您可以使用內部.some()調用循環遍歷您的array1並在找到匹配項時從該調用返回true ,而不是硬編碼?

 const array1 = ["?", "!", "."]; const array2 = ["live.", "ali!", "harp", "sharp%", "armstrong","yep?"]; const res = array2.filter((x) => array1.some(punc => x.endsWith(punc))); console.log(res);

上面,當您從.some()回調返回true (或真值)時, .some()方法將返回true ,否則如果您從不返回 true ,它將返回false ,從而丟棄它。

暫無
暫無

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

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