Get the App
SLTechnology News&Howtos  ›  Development  › 

How does es6 determine whether an element is in an array

Shulou Source: shulou.com Published: 2022-05-31 20:47:12 09月24日 Update

This article introduces the knowledge of "how to determine whether an element is in an array by es6". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Judgment method: 1, use "arr.includes (value)", it exists if true is returned; 2, use "arr.find (function (v) {if (value {/ / true}})" statement; 3, use "arr.some (I = > true value)", and exist if true is returned.

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

In es6, you can use includes, find, and some methods to determine whether an element is in an array. Let's introduce it in detail.

Method 1: use the includes method of es6

The 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 find

FromIndex: the index location at which to start the search.

Example:

Arr = [1, arr.includes 2, 3, 4] console.log (arr.includes (5))

As you can see, the return value of true indicates that element 5 is in the array.

Method 2: use the find method of es6

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

The find () method calls the function once for each element in the array:

When the element in the array returns true when the condition is tested, find () returns the element that meets the condition, and the subsequent value does not call the execution function.

Return undefined if there are no eligible elements

Example:

Var arr = [1, value, 3, 4, 5] arr.find (function (value) {if (value==5) {console.log ("specified elements in the array");}})

Method 3: use the some method of es6

The some () method is used to detect whether there are elements in the array that meet the specified conditions, returning true if they exist and false if they do not exist.

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

As you can see, the return value of false indicates that the element is not in the array.

That's all for "how es6 determines whether an element is in an array". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Tags: Elements methods arrays conditions content functions more knowledge examples testing practical learned and then first-time functions locations dilemmas reality situations tutorials articles Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno vpn Docker Shulou Technology Xiaomi Shulou Information