How to determine whether an array has a certain value in es6

青灯夜游
Release: 2022-03-23 16:10:56
Original
3415 people have browsed it

Judgment method: 1. Use the "arr.includes(element value)" statement. If the return value is true, then there is an item in the array; 2. Use "arr.findIndex((v)=> ;{return v==element value;})" statement, if the return value is not "-1", then the array contains an item.

How to determine whether an array has a certain value in es6

The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.

es6 Determine whether the array has a certain item value

Method 1: Use the includes() method

includes() method is used to determine whether an array contains a specified value and returns true or false. Syntax:

array.includes(searchElement, fromIndex);
Copy after login
  • searchElement: the element to be found;

  • fromIndex: the index position to start the search, which can be omitted, and the default value is 0.

Example:

var arr=[2, 9, 7, 8, 9];
if(arr.includes(9)){
	console.log("数组中有指定值");
}
else{
	console.log("数组中没有指定值");
}
Copy after login

How to determine whether an array has a certain value in es6

Method 2: Using the findIndex() method

The findIndex() method returns the index of the first element in the array that satisfies the provided test function. Otherwise return -1.

var arr=[2, 9, 7, 8, 9];
var ret = arr.findIndex((v) => {
    return v == 1;
});
if(ret!=-1){
	console.log("数组中有指定值");
}
else{
	console.log("数组中没有指定值");
}
Copy after login

How to determine whether an array has a certain value in es6

[Related recommendations: javascript video tutorial, web front-end

The above is the detailed content of How to determine whether an array has a certain value in es6. 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