0

我希望运行一个存在于我的每个数组元素上的函数。
我知道它可以通过 for 循环、each 和 map 来完成,但这些都不是追求纯粹的函数式方法。例如,使用 map 它看起来像这样:
var a = [1,2,3].map(function(item) { item.funcName(params); });

我不关心这些函数的返回值

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

纯JS中有这样的东西吗?ExtJS中有这样的东西吗?(我有。加载版本。4.1)

谢谢!

4

3 回答 3

2

在纯 Js 中,您可以将函数“map”添加到 Array 对象原型

在这个例子中,我对数组的每个元素进行 sqrt

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 );
于 2012-03-28T12:18:25.817 回答
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 许可下发布的,你可以在没有任何不良业力的情况下提升

于 2012-03-28T13:15:01.737 回答
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

于 2013-01-08T00:26:58.660 回答