Home > Web Front-end > JS Tutorial > body text

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

青灯夜游
Release: 2023-01-07 11:46:52
Original
5404 people have browsed it

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("给定值不在数组中");
}
Copy after login

Output result:

给定值在数组中
Copy after login
Copy after login

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("给定值不在数组中");
}
Copy after login

Output results:

给定值在数组中
Copy after login
Copy after login

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("给定值不在数组中");
}
Copy after login

Output result:

给定值不在数组中
Copy after login

[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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template