3 回答

TA貢獻1794條經驗 獲得超8個贊
運算符不是可分配的。函數參數只是作為表達式計算,因此您的調用等效于:||
var temp = "dogs"||"cats"||"birds"||"fish"||"frogs"; x.includes(temp)
一系列操作的值是該系列中的第一個真值。由于所有非空字符串都是真實的,因此這等效于:||
var temp = "dogs"; x.includes(temp)
您需要在調用每個字符串的結果上使用:||
includes
x.includes("dogs") || x.includes("cats") || x.includes("birds") ...
您可以使用數組方法簡化此操作:some()
["dogs","cats","birds","fish","frogs"].some(species => x.includes(species))

TA貢獻1951條經驗 獲得超3個贊
includes只查找一個字符串。您可以使用 .matchAll() 函數,該函數返回所有匹配結果的迭代器
const regex = /dogs|cats|birds|fish|frogs/g;
const str = 'the dogs, cats, fish and frogs all watched birds flying above them';
const exists = [...str.matchAll(regex)].length > 0;
console.log(exists);

TA貢獻1848條經驗 獲得超6個贊
對于這種情況,使用正則表達式和所需的布爾結果,RegExp#test派上用場。
此方法不返回迭代器,并且不需要數組即可獲取迭代器的長度。
const
regex = /dogs|cats|birds|fish|frogs/g,
str = 'the dogs, cats, fish and frogs all watched birds flying above them',
exists = regex.test(str);
console.log(exists);
添加回答
舉報