JavaScript判断数组对象是否含有某个值的方法(6种)
    		       		warning:
    		            这篇文章距离上次修改已过450天,其中的内容可能已经有所变动。
    		        
        		                
                在JavaScript中,你可以使用多种方法来判断数组是否包含某个值。以下是6种常见的方法:
- 使用 
indexOf()方法: 
let array = [1, 2, 3, 4, 5];
let value = 3;
 
if (array.indexOf(value) !== -1) {
  console.log('数组包含该值');
} else {
  console.log('数组不包含该值');
}- 使用 
includes()方法: 
let array = [1, 2, 3, 4, 5];
let value = 3;
 
if (array.includes(value)) {
  console.log('数组包含该值');
} else {
  console.log('数组不包含该值');
}- 使用 
find()方法: 
let array = [1, 2, 3, 4, 5];
let value = 3;
 
if (array.find(item => item === value)) {
  console.log('数组包含该值');
} else {
  console.log('数组不包含该值');
}- 使用 
some()方法: 
let array = [1, 2, 3, 4, 5];
let value = 3;
 
if (array.some(item => item === value)) {
  console.log('数组包含该值');
} else {
  console.log('数组不包含该值');
}- 使用循环遍历数组:
 
let array = [1, 2, 3, 4, 5];
let value = 3;
let found = false;
 
for (let i = 0; i < array.length; i++) {
  if (array[i] === value) {
    found = true;
    break;
  }
}
 
if (found) {
  console.log('数组包含该值');
} else {
  console.log('数组不包含该值');
}- 使用 
Array.prototype.find和===结合try...catch处理异常: 
let array = [1, 2, 3, 4, 5];
let value = 3;
 
try {
  array.find(item => item === value);
  console.log('数组包含该值');
} catch (e) {
  console.log('数组不包含该值');
}以上6种方法都可以用来判断JavaScript数组是否包含某个值,你可以根据实际情况选择最适合的方法。
评论已关闭