Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I determine if an element is contained in an Array without looping?

How can I check whether a particular element is inside an array? I don't want to manually write a loop for this; instead I want to use a JavaScript built-in function, maybe something equivalent to

new Array(0,1,2,3,6,9,12,15,18).Contains(5)  //return false
new Array(0,1,2,3,6,9,12,15,18).Contains(1)   //return true
like image 927
Graviton Avatar asked Dec 18 '25 03:12

Graviton


1 Answers

The Array object does have an indexOf function, that will return -1 if the object does not exist. However, IE does not support this function.

Regardless, how do you think it is going to locate the item under the scenes? It will have to loop! Just because there's a built-in function does not mean that it is magical.

like image 53
Josh Stodola Avatar answered Dec 20 '25 18:12

Josh Stodola



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!