Home >Web Front-end >JS Tutorial >How to determine if a given value is in an array in javascript

How to determine if a given value is in an array in javascript

青灯夜游
青灯夜游Original
2021-09-02 18:44:295448browse

Judgment method: 1. Use the includes() method, syntax "arr.includes('value')", if it is in the array, return true; 2. Use "arr.indexOf("value")" Or the "arr.lastIndexOf("value")" statement, if the return value is greater than 0, it is in the array.

How to determine if a given value is in an array in javascript

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

Method 1: Use the includes() method of the array

includes() method is used to determine whether an array contains a specified value. If so, it returns true, otherwise false.

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

Output result:

给定值在数组中

Method 2: Using the indexOf() or lastIndexOf() method of the array

indexOf() method Returns the first occurrence of a specified element in an array. If the element to be retrieved does not appear, the method returns -1.

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

var fruits = ['苹果',"香蕉", '榴莲', '橘子', '菠萝蜜',"梨子"];
var b = fruits.indexOf("橘子");
if (b>0) {
	console.log("给定值在数组中");
}else{
	console.log("给定值不在数组中");
}

Output results:

给定值在数组中

The lastIndexOf() method can search for elements in the array and return the position where it last appeared. If the element to be retrieved does not appear, the method returns -1.

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

var fruits = ['苹果',"香蕉", '榴莲', '橘子', '菠萝蜜',"梨子"];
var b = fruits.lastIndexOf("葡萄");
if (b>0) {
	console.log("给定值在数组中");
}else{
	console.log("给定值不在数组中");
}

Output result:

给定值不在数组中

[Recommended learning: javascript advanced tutorial]

The above is the detailed content of How to determine if a given value is in an array in javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn