indexOf()
MethodYou can use the indexOf()
method to check whether a given value or element exists in an array or not. The indexOf()
method returns the index of the element inside the array if it is found, and returns -1 if it not found. Let's take a look at the following example:
<script>
var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
// Check if a value exists in the fruits array
if(fruits.indexOf("Mango") !== -1){
alert("Value exists!")
} else{
alert("Value does not exists!")
}
</script>
ES6 has introduced the includes()
method to perform this task very easily. But, this method returns only true
or false
instead of index number, as you can see here:
<script>
var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
alert(fruits.includes("Banana")); // Outputs: true
alert(fruits.includes("Coconut")); // Outputs: false
alert(fruits.includes("Orange")); // Outputs: true
alert(fruits.includes("Cherry")); // Outputs: false
</script>
Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on harsukh21@gmail.com
How to add elements to the end of an array in PHP
Use the PHP array_push() funct...How to Change the Text of a Button using jQuery
Use the jQuery prop() and ...How to get the value of a textarea in jQuery
Use the jQuery val() method You can u...How to Verify Aadhar Card Number without any API?
In this article, i will share with you h...How to create jQuery slide up and down toggle effect
Use the jQuery slideUp() and&n...