SitePoint Sponsor

User Tag List

Results 1 to 2 of 2

Hybrid View

  1. #1
    doRighteousDeeds++
    Join Date
    Aug 2006
    Location
    تركيا Turkey Türkiye
    Posts
    266
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Array.prototype.map = function(func, thisVal)

    How to call this function? Thanks...
    Code:
      
    <script type="text/javascript" >
    	
    if (!Array.prototype.map)
    	Array.prototype.map = function(func, thisVal) {
    		var len = this.length;
    		var ret = new Array(len);
    		for (var i = 0; i < len; i++)
    			ret[i] = func.call(thisVal, this[i] || this.charAt && this.charAt(i), i, this);
    		return ret;
    	};
    	
    </script>

  2. #2
    SitePoint Wizard silver trophy kyberfabrikken's Avatar
    Join Date
    Jun 2004
    Location
    Copenhagen, Denmark
    Posts
    6,157
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Code:
    var result = [1,2,3].map(function(val) {
      return val + 10;
    });
    alert(result); // [11,12,13]
    It's a bad idea to modify prototypes of builtins, this way. You can easily rewrite the function to:
    Code:
    map = function(arr, func, thisVal) {
      var len = arr.length;
      var ret = new Array(len);
      for (var i = 0; i < len; i++) {
        ret[i] = func.call(thisVal, arr[i] || arr.charAt && arr.charAt(i), i, arr);
      }
      return ret;
    };
    Usage:
    Code:
    var result = map([1,2,3], function(val) {
      return val + 10;
    });
    alert(result); // [11,12,13]


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •