Copyright © tutorialspoint.com

Javascript Array map() Method

previous next

Advertisements


Description:

Javascript array map() method creates a new array with the results of calling a provided function on every element in this array.

Syntax:

array.map(callback[, thisObject]);

Here is the detail of parameters:

Return Value:

Returns created array.

Compatibility:

This method is a JavaScript extension to the ECMA-262 standard; as such it may not be present in other implementations of the standard. To make it work you need to add following code at the top of your script:

if (!Array.prototype.map)
{
  Array.prototype.map = function(fun /*, thisp*/)
  {
    var len = this.length;
    if (typeof fun != "function")
      throw new TypeError();

    var res = new Array(len);
    var thisp = arguments[1];
    for (var i = 0; i < len; i++)
    {
      if (i in this)
        res[i] = fun.call(thisp, this[i], i, this);
    }

    return res;
  };
}

Example:

<html>
<head>
<title>JavaScript Array map Method</title>
</head>
<body>
<script type="text/javascript">
if (!Array.prototype.map)
{
  Array.prototype.map = function(fun /*, thisp*/)
  {
    var len = this.length;
    if (typeof fun != "function")
      throw new TypeError();

    var res = new Array(len);
    var thisp = arguments[1];
    for (var i = 0; i < len; i++)
    {
      if (i in this)
        res[i] = fun.call(thisp, this[i], i, this);
    }

    return res;
  };
}

var numbers = [1, 4, 9];
var roots = numbers.map(Math.sqrt);

document.write("roots is : " + roots ); 

</script>
</body>
</html>

This will produce following result:

roots is : 1,2,3  

To understand it in better way you can Try it yourself.


previous next

Copyright © tutorialspoint.com