在JavaScript中,有多种方法可以用来判断一个元素是否存在于数组中。以下是其中的一些方法:
1. 使用 Array.prototype.includes() 方法
includes() 方法用于判断一个数组是否包含一个指定的值,根据情况,如果需要区分大小写,它会返回 true 或 false。
const array = [1, 2, 3, 4, 5];
const element = 3;
if (array.includes(element)) {
console.log(`数组中包含元素 ${
element}`);
} else {
console.log(`数组中不包含元素 ${
element}`);
}
2. 使用 Array.prototype.indexOf() 或 Array.prototype.lastIndexOf() 方法
indexOf() 和 lastIndexOf() 方法会返回指定元素在数组中的索引值,如果元素不存在则返回 -1。


2万+

被折叠的 条评论
为什么被折叠?



