Get the App
SLTechnology News&Howtos  ›  Development  › 

How does es6 determine whether an array contains a child element

Shulou Source: shulou.com Published: 2022-06-01 06:48:51 10月03日 Update

This article mainly introduces es6 how to determine whether the array contains a child element, the article is very detailed, has a certain reference value, interested friends must read it!

Method: 1, use indexOf () function, syntax "array object .indexOf (value)", if return element position contains, if return "- 1" does not contain; 2, use includes () function, syntax "array object .indexOf (value)", return true contains, otherwise does not contain.

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

Es6 determines whether the array contains a child element.

Method 1: use the indexOf () function

IndexOf is used to find the location of an element and returns-1 if it does not exist.

Const arr = ['axiao,' baked, 'cased,' dashed, 'eyed,' faded, 'gashed,' hacked, 'ified,' jaded, 'kink, NaN] console.log (arr.indexOf (' c')) console.log (arr.indexOf ('z'))

Note: the indexOf () function has two small deficiencies in judging whether an array contains an element.

The first is that it returns-1 and the position of the element to indicate whether it is included or not. It is fine in terms of positioning, but it is not semantic enough.

Another problem is that it is not possible to determine whether there is an element of NaN.

Const arr = ['averse,' baked, 'cased,' dashed, 'eyed,' faded, 'grubbed,' hacked, 'ified,' jaded, 'kicking, NaN] console.log (arr.indexOf (NaN))

Method 2: use the includes () function

The includes () function can be used to detect whether an array contains a value.

In addition to being unable to locate, the includes () function solves the above two problems of indexOf. It directly returns true or false to indicate whether it contains elements, which is also valid for NaN.

Const arr = ['asides,' baked, 'cached,' dudes, 'eBay,' fags, 'gags,' hacks, 'iFalls,' jacks, 'Kids, NaN] console.log (arr.includes (' c')) console.log (arr.includes ('z')) console.log (arr.includes (NaN))

The above is all the content of the article "how es6 determines whether an array contains a child element". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

Tags: Element array function size position method problem two content object article grammar location valid not enough value interest boy buddy that is Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno vpn Shulou Tech Info Docker Shulou Technology Microsoft