jQuery Utility methods

by anandhinava

JavaScript

$(function() {

    var str = $.trim( "    lots of extra whitespace    " );
    console.log(str); // Returns "lots of extra whitespace"
    
    $.each([ "foo", "bar", "baz" ], function( idx, val ) {
        console.log( "element %d is %s", idx, val);
    });
     
    $.each({ foo: "bar", baz: "bim" }, function( k, v ) {
        console.log( k + " : " + v );
    });
    
    var myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
    var myIdx = $.inArray( 4, myArray );
 
    if ( myIdx !== -1 ) {
        console.log( "found %d at index %d", 4, myIdx );
    }
    
    var oddArray = $.grep(myArray, function(n) {
        return n % 2 != 0;
    });
    
    console.log(oddArray);
 
    var powArray = $.map(myArray, function(n) {
      return Math.pow(n,2);
    });

    console.log(powArray);
    
    var firstObject = { foo: "bar", a: "b" };
    var secondObject = { foo: "baz" };
     
    // changes first object
    var newObject = $.extend( firstObject, secondObject );
     
    console.log( firstObject.foo ); // "baz"
    console.log( newObject.foo ); // "baz"
    
    var firstObject = { foo: "bar", a: "b" };
    var secondObject = { foo: "baz" };
     
    // does not change first object
    var newObject = $.extend( {}, firstObject, secondObject );
     
    console.log( firstObject.foo ); // "bar"
    console.log( newObject.foo ); // "baz"
    
    var myFunction = function() {
        console.log( this );
    };
    var myObject = {
        foo: "bar"
    };
     
    myFunction(); // window
     
    var myProxyFunction = $.proxy( myFunction, myObject );
     
    myProxyFunction(); // myObject

});