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:
- callback : Function that produces an element of the new Array from an element of the current one.
- thisObject : Object to use as this when executing callback.
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
+JavaScript +JavaScript Frameworks Links +Javascript Development
+JavaScript's and More, Software and Marketing +JavascriptU +JavaScriptOn
+Javascript Problems +JavaScriptOn
+javaScript is a creek in West Virginia in the summe
No comments: