Intellipaat Back

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

Below is my code to check if a value exists in an array:

Array.prototype.contains = function(obj) {

    var i = this.length;

    while (i--) {

        if (this[i] == obj) {

            return true;

        }

    }

    return false;

}

This is my code for array values and function call: 

arrValues = ["Sam","Great", "Sample", "High"]

alert(arrValues.contains("Sam"));

The function always returns false. Can anyone tell me what I’m doing wrong here? 

1 Answer

0 votes
by (19.7k points)

Check the below code snippet:

var contains = function(needle) {

    // Per spec, the way to identify NaN is that it is not equal to itself

    var findNaN = needle !== needle;

    var indexOf;

    if(!findNaN && typeof Array.prototype.indexOf === 'function') {

        indexOf = Array.prototype.indexOf;

    } else {

        indexOf = function(needle) {

            var i = -1, index = -1;

            for(i = 0; i < this.length; i++) {

                var item = this[i];

                if((findNaN && item !== item) || item === needle) {

                    index = i;

                    break;

                }

            }

            return index;

        };

    }

    return indexOf.call(this, needle) > -1;

};

This is the code to take array values and function call:

var myArray = [0,1,2],

    needle = 1,

    index = contains.call(myArray, needle); // true

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

Related questions

0 votes
1 answer
0 votes
1 answer

Browse Categories

...