How to detect whether there is an element in an array in es6

青灯夜游
Release: 2022-04-11 13:00:37
Original
4682 people have browsed it

Detection method: 1. Use the "arr.indexOf("element value")" statement, if the element index is returned, it exists; 2. Use "arr.includes("value")", if it exists, return true; 3. Use the for loop statement to traverse the array, and use the if statement and the "==" operator to determine whether the array element is the specified value.

How to detect whether there is an element in an array in es6

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

es6 Detect whether there is an element in the array

Method 1: array.indexOf

This method determines whether a certain value exists in the array. If it exists, it returns the subscript of the array element, otherwise it returns -1.

var arr=[1,2,3,4];
var index=arr.indexOf(3);
console.log(index);
Copy after login

How to detect whether there is an element in an array in es6

Method 2: array.includes(searcElement[,fromIndex])

This method determines Whether there is a certain value in the array, if it exists, return true, otherwise return false

#
var arr=[1,2,3,4];
if(arr.includes(3))
    console.log("存在");
else
    console.log("不存在");
Copy after login

How to detect whether there is an element in an array in es6

Method 3: Use for loop and if

var arr=[1,2,3,4];
var k=0;
for(var i=0;i<arr.length;i++){
    if(arr[i]==3)
        k=1;
}
if(k)
    console.log("存在");
else
    console.log("不存在");
Copy after login

How to detect whether there is an element in an array in es6

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

The above is the detailed content of How to detect whether there is an element in an array 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