Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (9.5k points)

Below is the code I’ve:

function inArray(needle,haystack)

{

    var count=haystack.length;

    for(var i=0;i<count;i++)

    {

        if(haystack[i]===needle){return true;}

    }

    return false;

}

Can anyone tell me if there is a better way to do it?

1 Answer

0 votes
by (19.7k points)

Use ECMAScript 2016 which has an includes() method for arrays which solves the problem: 

[1, 2, 3].includes(2);     // true

[1, 2, 3].includes(4);     // false

[1, 2, 3].includes(1, 2);  // false (second parameter is the index position in this array

Interested in Java? Check out this Java tutorial by Intellipaat.  

Related questions

Browse Categories

...