js判断某个值是否在数组中
时间: 2024-01-29 15:03:19 浏览: 33
可以使用JavaScript中的两种方法来判断某个值是否在数组中:
1.使用indexOf()方法,如果存在则返回该元素的下标,否则返回-1。
```javascript
let arr = ['something', 'anything', 'nothing', 'anything'];
let index = arr.indexOf('nothing');
console.log(index); // 输出:2
```
2.使用includes()方法,如果存在则返回true,否则返回false。
```javascript
let arr = ['something', 'anything', 'nothing', 'anything'];
let isExist = arr.includes('nothing');
console.log(isExist); // 输出:true
```
相关问题
js 判断某个值是否在数组中
可以使用 JavaScript 的数组方法 `includes()` 来判断某个值是否在数组中,示例如下:
```js
const arr = [1, 2, 3];
const value = 2;
if (arr.includes(value)) {
console.log(`${value} 存在于数组中`);
} else {
console.log(`${value} 不存在于数组中`);
}
```
输出结果为:
```
2 存在于数组中
```
如果要判断的值不在数组中,输出结果为:
```
2 不存在于数组中
```
另外,如果需要兼容低版本的浏览器,可以使用 `indexOf()` 方法来判断,示例如下:
```js
if (arr.indexOf(value) !== -1) {
console.log(`${value} 存在于数组中`);
} else {
console.log(`${value} 不存在于数组中`);
}
```
jquery判断某个元素是否在数组中
可以使用 jQuery 的 `inArray()` 函数来判断某个元素是否在数组中。该函数的语法如下:
```javascript
jQuery.inArray(value, array)
```
其中,`value` 是要查找的值,`array` 是要查找的数组。如果 `value` 在 `array` 中,该函数会返回 `value` 在 `array` 中的索引值(从 0 开始),否则返回 -1。例如:
```javascript
var myArray = ["apple", "banana", "orange"];
var myElement = "banana";
if (jQuery.inArray(myElement, myArray) !== -1) {
console.log(myElement + " is in the array.");
} else {
console.log(myElement + " is not in the array.");
}
```
输出结果为:
```
banana is in the array.
```