javascript中如何判断 ['1', '2', '3']中是否有‘1’,如果有则返回true,如果没有则返回false
时间: 2023-12-09 09:03:49 浏览: 12
可以使用数组的 `includes` 方法来判断:
```javascript
const arr = ['1', '2', '3'];
const hasOne = arr.includes('1');
console.log(hasOne); // true
```
或者使用 `indexOf` 方法:
```javascript
const arr = ['1', '2', '3'];
const hasOne = arr.indexOf('1') !== -1;
console.log(hasOne); // true
```
如果要严格匹配类型,可以使用 `===` 进行比较:
```javascript
const arr = ['1', '2', '3'];
const hasOne = arr.includes(1) === true;
console.log(hasOne); // false
```
相关问题
拿一个ID 在数组对面比对 如果有 则返回false 没有则返回true
可以使用 JavaScript 中的 Array.includes 方法来实现这个功能。该方法可以判断一个数组是否包含特定的元素。具体代码如下:
```javascript
function checkID(array, id) {
return !array.includes(id);
}
// 示例用法
const ids = [1, 2, 3, 4];
console.log(checkID(ids, 3)); // false
console.log(checkID(ids, 5)); // true
```
上面的代码中,checkID 函数接受两个参数,第一个是存储 ID 的数组,第二个是需要比对的 ID。函数首先调用 Array.includes 方法来判断数组中是否包含该 ID,如果包含则返回 false,否则返回 true。最后,我们可以通过示例用法来测试函数的正确性。
编写一个 JavaScript 函数,判断指定元素是否具有指定的属性,如果有则返回 true,否则返回 false
可以使用 JavaScript 中的 `hasAttribute()` 方法来判断一个元素是否具有指定的属性,代码如下:
```javascript
function hasAttr(element, attr) {
return element.hasAttribute(attr);
}
```
其中,`element` 表示要判断的元素,`attr` 表示要判断的属性名。调用该函数,如果元素具有指定的属性,则返回 `true`,否则返回 `false`。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)