js 如何判断字符串在不在字符串数组中
时间: 2024-04-30 13:19:12 浏览: 97
js判断一个字符串是否包含一个子串的方法
可以使用`Array.includes()`方法来判断一个字符串是否在一个字符串数组中,示例如下:
```js
const arr = ['apple', 'banana', 'orange'];
const str = 'apple';
if (arr.includes(str)) {
console.log(`${str} exists in the array.`);
} else {
console.log(`${str} does not exist in the array.`);
}
```
输出结果为:
```
apple exists in the array.
```
如果要判断多个字符串是否在数组中,可以通过循环遍历每个字符串,再使用`Array.includes()`方法判断是否存在,示例如下:
```js
const arr = ['apple', 'banana', 'orange'];
const strs = ['apple', 'pear', 'banana'];
for (let str of strs) {
if (arr.includes(str)) {
console.log(`${str} exists in the array.`);
} else {
console.log(`${str} does not exist in the array.`);
}
}
```
输出结果为:
```
apple exists in the array.
pear does not exist in the array.
banana exists in the array.
```
阅读全文