Monday, December 12, 2011

in_array in javascript


 /*
   *PHP in_array function  in  javascript
   */
   function in_array (needle, haystack, argStrict) {
    // Checks if the given value exists in the array
    //
    // *     example 1: in_array('Raj', ['Kumar', 'Tom', 'Raj']);
    // *     returns 1: true
    // *     example 2: in_array('Hari', {0: 'Kathir', Hari: 'Passat', 1: 'Raj'});
    // *     returns 2: false
    // *     example 3: in_array(1, ['1', '2', '3']);
    // *     returns 3: true
    // *     example 3: in_array(1, ['1', '2', '3'], false);
    // *     returns 3: true
    // *     example 4: in_array(1, ['1', '2', '3'], true);
    // *     returns 4: false
     var key = '',
        strict = !! argStrict;

     if (strict) {
        for (key in haystack) {
            if (haystack[key] === needle) {
                return true;
            }
        }
     } else {
        for (key in haystack) {
            if (haystack[key] == needle) {
                return true;
            }
        }
     }

     return false;
   }

No comments:

Post a Comment