簡體   English   中英

如何正確使用JS包含

[英]How to use properly JS includes

我有以下腳本,我有一個數組,我需要過濾我的特定關鍵字,在這種情況下GitHub ,代碼結果為 false,而我需要調整它以返回 true。

我究竟做錯了什么? 如何解決?

 const array1 = ["[GitHub](https://github.com/xxx", 2, 3]; console.log(array1.includes('GitHub'));

正如評論.includes不是預期的功能。 它進行精確搜索,而您正在尋找部分搜索。

array.some + String.includes

正如@Nick Parsons正確指出的那樣,由於數字沒有.includes ,我們必須將其轉換為字符串。

只是提醒一下,第一個片段,如果一個數字出現在有效匹配之前,它將引發錯誤。

 const array1 = [5, "[GitHub](https://github.com/xxx", 2, 3]; console.log(array1.some((str) => str.toString().includes('GitHub')));


字符串.includes

如果數組中有原始值,則可以直接使用string.includes

正如@Max所評論的

“部分搜索”是一個相當具有誤導性的術語。 按謂詞搜索就是它的真正含義

 const array1 = ["[GitHub](https://github.com/xxx", 2, 3]; console.log(array1.join().includes('GitHub'));

請注意, sytring.includes是一個區分大小寫的函數,並且會因大小寫不匹配而失敗。

如果您希望進行不區分大小寫的搜索,請將兩個字符串值轉換為相同的大小寫或使用正則表達式

 const array1 = ["[GitHub](https://github.com/xxx", 2, 3]; function test(str) { const regex = new RegExp(str, 'i') console.log(regex.test(array1.join())); } test('GitHub') test('git') test('hub')

請參閱文檔

include() 方法確定數組是否在其條目中包含某個值,並根據需要返回 true 或 false。

雖然"GitHub"是其中一個值的子字符串,但它不是該值的完全匹配。 您不能為此使用includes


find方法可以讓你通過它可以做一個字符串匹配(使用的功能includes一個字符串的方法。

 const array1 = ["[GitHub](https://github.com/xxx", 2, 3]; const results = array1.find(element => element.includes('GitHub')); const match = !!results; // Convert to boolean console.log(results); console.log(match);

暫無
暫無

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

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