Home > Web Front-end > Front-end Q&A > How to determine whether an element is in an array in es6

How to determine whether an element is in an array in es6

青灯夜游
Release: 2022-10-14 18:18:33
Original
4265 people have browsed it

Judgment method: 1. Use "arr.includes(value)", if it returns true, it exists; 2. Use "arr.find(function(v){if(v==value{//true }})" statement; 3. Use "arr.some(i=>i===value)", if it returns true, it exists.

How to determine whether an element is in an array in es6

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

In es6, you can use the includes, find, and some methods to determine whether an element is in an array. Here is a detailed introduction.

Method 1: Use the includes method of es6

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 searching.

Example:

arr = [1,2,3,4,5]
console.log(arr.includes(5));
Copy after login

How to determine whether an element is in an array in es6

You can see that the return value is true, which means that element

5 is in the array.

Method 2 : Use the find method of es6

find() method returns the value of the first element of the array that passes the test (judged within the function).

find() method is in the array Each element of Call the execution function.

  • If there is no element that meets the conditions, return undefined

  • Example:

    var arr = [1,2,3,4,5]
    arr.find(function(value){
    	if(value==5){
    		console.log("指定元素在数组中");
    	}
    })
    Copy after login

Method 3: Use the some method of es6

How to determine whether an element is in an array in es6

The some() method is used to detect whether there is an element that meets the specified conditions in the array. If it exists, it returns true, if it does not exist, it returns false.

arr = [1,2,3,4,5];
let istrue= arr.some(item => item === 45);
console.log(istrue);
Copy after login

You can see that the return value is false, which means the element is not in the array.

[Related recommendations:How to determine whether an element is in an array in es6javascript video tutorial

web front end

The above is the detailed content of How to determine whether an element is in an array in es6. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
es6
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