Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

js 判断元素是否在数组中

作者:冷血杀手   发布日期:2025-12-01   浏览:45

// 使用 Array.prototype.includes() 方法判断元素是否在数组中

const array = [1, 2, 3, 4, 5];
const element = 3;

if (array.includes(element)) {
  console.log(`${element} 存在于数组中`);
} else {
  console.log(`${element} 不存在于数组中`);
}

// 解释说明:
// includes() 方法用于判断数组是否包含某个指定的值,根据情况返回 true 或 false。
// 这个方法非常适合用来检查一个数组中是否存在某个特定的元素。

如果需要兼容性更好的解决方案(例如在不支持 includes 的旧浏览器中),可以使用 indexOf 方法:

// 使用 Array.prototype.indexOf() 方法判断元素是否在数组中

const array = [1, 2, 3, 4, 5];
const element = 3;

if (array.indexOf(element) !== -1) {
  console.log(`${element} 存在于数组中`);
} else {
  console.log(`${element} 不存在于数组中`);
}

// 解释说明:
// indexOf() 方法返回数组中某个指定元素的第一个索引,如果不存在则返回 -1。
// 通过检查返回值是否为 -1 来判断元素是否存在于数组中。

上一篇:js 字符串

下一篇:js 数组是否包含某个元素

大家都在看

js 数组对象排序

js 数组删掉第一个值

js fill

js 数组连接

js json数组

js 数组复制

js 复制数组

js 数组拷贝

js 对象数组合并

js 对象转数组

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站