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

js 数组包含某个元素

作者:空白篇pia~   发布日期:2026-06-13   浏览:75

// 检查数组是否包含某个元素

// 使用 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() 方法返回一个布尔值,表示数组是否包含指定的元素。
// 它是 ES2016 引入的新方法,适用于现代浏览器和 Node.js 环境。

// 如果需要兼容性更好的方法,可以使用 Array.prototype.indexOf()
if (array.indexOf(element) !== -1) {
  console.log(`数组中包含元素 ${element}`);
} else {
  console.log(`数组中不包含元素 ${element}`);
}

// indexOf() 方法返回指定元素在数组中的第一个索引,如果不存在则返回 -1。

上一篇:js 给数组添加元素

下一篇:js 数组最后一个元素

大家都在看

js 数组打乱顺序

js 两个数组取交集

js 数组对象排序

js 对象数组排序

js 数组删掉第一个值

js fill

js fill方法

js 数组连接

js json数组

js 数组复制

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

Laravel 中文站