JS Check if an array contains an value or object JavaScript

Tthis code works in all previous versions of browsers

// use ===
function contains(arr, valueOrObject) {
    for (var i = 0; i < arr.length; i++) {
        if (arr[i] === valueOrObject) {
            return true;
        }
    }
    return false;
}
 
// example of usage
// array of strings and numbers
    var arr = new Array('5', 3, '7', 12);
// true
    if (contains(arr, '5')) {
        alert('Contains string 5');
    } else {
        alert('Does not contain string 5');
    }
 
// false
    if (contains(arr, 5)) {
        alert('Contains number 5');
    } else {
        alert('Does not contain number 5');
    }
 
// true
    if (contains(arr, 12)) {
        alert('Contains number 12');
    } else {
        alert('Does not contain number 12');
    }
This entry was posted in Javascript css html and tagged . Bookmark the permalink.


Comments are closed.

551 views