How does js determine whether the value is in the array

1. Use the includes() method of the array

The includes() method is used to determine whether an array contains a specified value, and return true if it is, otherwise false.

var fruits = ['苹果',"香蕉", '榴莲', '橘子', '菠萝蜜',"梨子"];
if(fruits.includes('榴莲')){
    console.log("该值在数组中");
} else {
    console.log("该值不在数组中"); 
}
 
// 输出结果:该值在数组中

For more introduction about the includes method, refer to the use of includes in js ( Use of includes in js_Usage of includes in js_Western Jin's no1 blog-CSDN blog )

2. Use the indexOf() or lastIndexOf() method of the array

2.1 indexOf() method

The indexOf() method returns the position of the first occurrence of a specified element in an array. If the element to be retrieved is not present, the method returns -1.

Implementation idea: Use this method to check the first occurrence of the specified value in the array, and if the position exists, include the given element. If -1 is returned, the given element is not included.

var fruits = ['苹果', "香蕉", '榴莲', '橘子', '菠萝蜜', "梨子"];
var b = fruits.indexOf("橘子");
 
if (b > -1) {
    console.log("该值在数组中");
} else {
    console.log("该值不在数组中");
}
 
// 输出结果:该值在数组中

2.2 lastIndexOf () method

The lastIndexOf() method searches for an element in an array and returns its last occurrence. If the element to be retrieved is not present, the method returns -1.

Implementation idea: Use this method to check the last position of the specified value in the array. If the position exists, the given element will be included; if -1 is returned, the given element will not be included.

var fruits = ['苹果', "香蕉", '榴莲', '橘子', '菠萝蜜', "梨子"];
var b = fruits.lastIndexOf("葡萄");
 
if (b > -1) {
    console.log("该值在数组中");
} else {
    console.log("该值不在数组中");
 
}
 
// 输出结果: 该值不在数组中

Guess you like

Origin blog.csdn.net/xijinno1/article/details/132094340