// 检查数组是否包含某个元素
// 使用 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 数组最后一个元素
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站