2012-03-28 118 views
0

我希望运行每个数组元素上存在的函数。
我知道它可以用for循环,each和map来完成,但是这些都没有追求纯粹的功能方法。 例如,地图会是这个样子:
var a = [1,2,3].map(function(item) { item.funcName(params); });
如何在Javascript中的每个数组元素上运行函数

我不关心这些功能

示例代码我希望我有返回值:
var a = [1,2,3].magicRun('funcName'[, paramsArray]);;

是纯JS中有这样的事情吗? ExtJS中有这样的事情吗? (我有效。加载版本4.1)

谢谢!

+1

你试过['Array.forEach'](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/forEach)? – Zeta 2012-03-28 10:18:04

+0

什么试图完全实现? 'magicRun'应该做什么?你期望这个'paramsArray'应该发生什么? – jAndy 2012-03-28 10:23:41

回答

1

没有什么完全像你想要什么纯JS,我不认为ExtJS的有它要么(但我从版本3.something没有用愤怒ExtJS的,所以有可能是)

MooTools但会将此invoke方法Array

invoke: function(methodName){ 
    var args = Array.slice(arguments, 1); 
    return this.map(function(item){ 
    return item[methodName].apply(item, args); 
    }); 
}, 

...这被MIT许可下发布的,可以解除无任何恶业

+0

虽然不是解决问题的办法,但它是一个答案这个问题......我接受。谢谢! – Nadav 2012-03-28 13:50:01

2

在纯的js,你可以添加功能“映射”到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); 
+0

这种方法对每个数组的项目(Math.sqrt)运行一个外部函数而不是项目本身的函数 – Nadav 2012-03-28 13:53:52

+0

这就是我理解它应该对不起:) – 2012-03-28 15:40:22

0
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); 
    } 
    }; 
} 

为例:

<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> 

来源:http://www.tutorialspoint.com/javascript/array_foreach.htm

相关问题