Reputation: 1185
I wish to run a function that exists on each of my array's elements.
I know it can be done with a for loop, an each, and map, but none of these pursue a pure functional approach.
for example, with map it would look something like this:
var a = [1,2,3].map(function(item) { item.funcName(params); });
I do not care about the return values of these functions
example code I wish I had:
var a = [1,2,3].magicRun('funcName'[, paramsArray]);;
Is there such a thing in pure JS? It there such a thing in ExtJS? (which I have avail. loaded ver. 4.1)
Thanks!
Upvotes: 0
Views: 4162
Reputation: 3947
if (!Array.prototype.forEach)
{
Array.prototype.forEach = function(fun /*, thisp*/)
{
var len = this.length;
if (typeof fun != "function")
throw new TypeError();
var thisp = arguments[1];
for (var i = 0; i < len; i++)
{
if (i in this)
fun.call(thisp, this[i], i, this);
}
};
}
exemple:
<html>
<head>
<title>JavaScript Array forEach Method</title>
</head>
<body>
<script type="text/javascript">
if (!Array.prototype.forEach)
{
Array.prototype.forEach = function(fun /*, thisp*/)
{
var len = this.length;
if (typeof fun != "function")
throw new TypeError();
var thisp = arguments[1];
for (var i = 0; i < len; i++)
{
if (i in this)
fun.call(thisp, this[i], i, this);
}
};
}
function printBr(element, index, array) {
document.write("<br />[" + index + "] is " + element );
}
[12, 5, 8, 130, 44].forEach(printBr);
</script>
</body>
</html>
source: http://www.tutorialspoint.com/javascript/array_foreach.htm
Upvotes: 0
Reputation: 12459
There's nothing exactly like what you want in pure JS, and I don't think ExtJS has it either (but I haven't used ExtJS in anger since version 3.something, so there might be)
MooTools however adds this invoke
method to Array
:
invoke: function(methodName){
var args = Array.slice(arguments, 1);
return this.map(function(item){
return item[methodName].apply(item, args);
});
},
...which being released under the MIT license, you can lift without any bad karma
Upvotes: 1
Reputation: 1182
In pure Js you can add the function "map" to Array object prototype
In this example I make the sqrt of every element of the array
if (!Array.prototype.map)
Array.prototype.map = function(fun)
{
var len = this.length;
if (typeof fun != "function")
throw new TypeError();
var res = new Array(len);
for (var i = 0; i < len; ++i)
res[i] = fun(this[i]);
return res;
};
var numbers = [1, 4, 9];
var roots = numbers.map(Math.sqrt);
//could be an alert
console.log("roots is : " + roots );
Upvotes: 2