[英]pass array to includes() javascript
我試圖找出一個字符串是否包含存儲在數組中的多個字符串.includes()
所以我試過了
let string = 'hello james';
console.log(string.includes(['hello', 'james']));
但它被返回為false
..當我知道字符串包含'你好'或'詹姆斯'這是否可能? 如何判斷字符串是否包含“hello”或“james”這個詞?
所以在偽代碼中,這看起來像string.includes('hello' || 'james');
基於文檔 , includes
第一個參數是字符串而不是數組。
你可以做:
如果要檢查字符串中是否存在數組中的每個字符串,可以使用every
並includes
組合
let string = 'hello james'; let toCheck = ['hello', 'james']; let result = toCheck.every(o => string.includes(o)); console.log(result);
如果要檢查字符串中是否存在數組中的至少一個條目,則可以使用some
而不是every
。
let string = 'hello james'; let toCheck = ['hello', 'james1']; let result = toCheck.some(o => string.includes(o)); console.log(result);
根據文檔 , str.includes
將string
作為第一個參數。
因此,當您傳遞數組時,它會將字符串數組轉換為單個字符串,並將該字符串用作includes函數的第一個參數。
只是為了證明這一點,
let string = "hello,james";
var array = ["hello", "james"]
console.log(string.includes(array)); // returns true, as array would be converted to "hello,james"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.