{return v== element Value;})" statement, if the return value is not "-1", then the array contains a certain item."/> {return v== element Value;})" statement, if the return value is not "-1", then the array contains a certain item.">
Home >Web Front-end >Front-end Q&A >How to determine whether an array has a certain value in es6
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.
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);
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("数组中没有指定值"); }
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("数组中没有指定值"); }
[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!