对列表/数组中的每个项目运行相同的函数

Run the same function on each item in a list / array

本文关键字:项目 运行 函数 列表 数组      更新时间:2023-09-26

Goal

有一个工作函数(JSFiddle)。在整个脚本中,函数多次按顺序运行。在这些实例中,我想合并很多重复的代码。

理想情况下,像这样更改代码:

functionName("First_item") + 
functionName("Second_item") + 
functionName("Third_item") + 

像这样:

functionName("First_item", "Second_item", "Third_item");

该函数将针对列表中的每个项目运行,因此结果相同,但代码更优雅且易于维护。

笔记:

  • 我不打算使用任何库(例如jQuery)来实现目标。

溶液

  1. Amit Joki的回答善意地指出我可以使用论据。当我实现代码时,修改后的函数(JSFiddle)只返回第一个参数/项的output字符串。

  2. 瓦尼斯的回答指出了最终的解决方案。

    • 通过在 for 循环中连接(连接)output字符串(使用 +=),从所有参数/项目的输出中创建一个字符串。
    • 通过将return放在 for 循环之外来返回串联输出。

工作解决方案(JSFiddle)。


谢谢

非常感谢大家的时间和帮助。我真的很感激!

利用Javascript的原型OOP:你可以将每个函数添加到Array本身,这样代码中的每个数组都会自动有一个固有的每个函数。

Array.prototype.each = function(callback){
    for (var i =  0; i < this.length; i++){
        callback(this[i]);
    }
}

用法:

myArray.each(myCoolFunction) ['something','somethingelse',somethingother'].each(myCoolFunction)

myArray.each( function (item) {
 // if your item has a method
 item.Something();
 // if you'd like to call a function on the item:
 doSomething(item);
});

警告:

由于 javascript 是一种异步语言,在各种浏览器中的解释方式不同,并且本质上以不同的方式处理原始对象和复杂对象,因此强烈建议使用下划线或 lodash。 您也可以创建自己的对象,但您需要确保传递的对象将由函数正确处理。 这可能包括解决方法或为通过each函数传递的不同对象类型创建特殊的回调函数。

有关更多信息:JavaScript 是按引用传递还是按值传递语言?

您应该认真考虑的库:

洛达什:https://lodash.com/docs#forEach

_([1, 2, 3]).forEach(function(num) { console.log(num); }).join(',');
// → logs each number and returns '1,2,3'
_.forEach({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { console.log(num); });
// → logs each number and returns the object (property order is not guaranteed across environments)

下划线:http://underscorejs.org/#each

_.each([1, 2, 3], alert);
=> alerts each number in turn...

你不需要数组。只需使用arguments

function functionName(){
   for(var i = 0; i < arguments.length; i++){
      // do something with arguments[i];
   }
}

然后你可以做

functionName("shot_type","shot_height","shot_angle","framed","scene_depth");

如果支持旧版IE版本不是问题,则P.S @codebox的解决方案有效。不知道他为什么删除它...所以把它放在这里,所以它会有所帮助。 他的回答是用forEach

["shot_type","shot_height","shot_angle","framed","scene_depth"].forEach(FunctionName);

编辑:查看您的小提琴,您在 for 循环中有一个返回 - 因此该函数将在第一次迭代后返回。将返回放在 for 之后,并将输出连接成一个字符串。

var output = "";
for(...){
    output += description_of_object + ": " + randomly_selected_item_from_object + ".'n";
}   
// return it
return output;

仅使用 Javascript:

var actions = ["shot_type","shot_height","shot_angle","framed","scene_depth"];
for (var i = 0; i < actions.length; i++){
  FunctionName(actions[i]);
}

使用 JQuery:

$.each(["shot_type","shot_height","shot_angle","framed","scene_depth"], function(index,value){
  FunctionName(value);
});

我还没有测试过它,但它应该可以工作。

若要避免代码中的冗余,请使用包含要通过函数并在循环中调用函数的值的数组。

var vals=["shot_type","shot_height","shot_angle","framed","scene_depth"];
for(var i=0; i<vals.length; i++)
{
    FunctionName(vals[i]);
}

如果要扩展函数(添加另一个参数),只需扩展 for 循环和数组结构即可。

或者,您可以使用值填充对象并在对象中处理此逻辑。但这只会在调用函数时有所不同。