How to implement Javascript ECMA 5's array.map() for sparse array?
<p>It should be quite easy to implement <code>array.map()</code> that is <a href="http://ecma-international.org/ecma-262/5.1/#sec-15.4.4.19" rel="nofollow">defined in ECMA-262</a>, which takes a function and this function will be called by 3 arguments: element value, index, the array.</p>

<p>But what about for sparse array?  Obviously we don't want to iterate from index 0 to 100,000 if only index 0, 1, 2, and 100,000 has an element and otherwise is sparse from index 3 to 99,999. I can think of using <code>arr.slice(0)</code> or <code>arr.concat()</code> to clone the array, and then put in the replaced values, but what if we don't use <code>slice</code> or <code>concat</code>, is there another way to do it? </p>

<p>The solution I came up with using <code>slice()</code> is:</p>

<pre><code>Array.prototype.collect = Array.prototype.collect || function(fn) {
    var result = this.slice(0);

    for (var i in this) {
      if (this.hasOwnProperty(i))
        result[i] = fn(this[i], i, this);  // 3 arguments according to ECMA specs
    }
    return result;
};
</code></pre>

<p>(<code>collect</code> is used to try out the code, as that's another name for <code>map</code> in some language)</p>
