Home >Web Front-end >Front-end Q&A >How to detect whether there is an element in an array in es6
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.
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);
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("不存在");
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("不存在");
[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!