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

Gre*_*reg 3 javascript function

目标

我有一个工作函数(JSFiddle).在整个脚本中的许多场合,该函数按顺序运行.在这些情况下,我想整合很多重复的代码.

理想情况下更改代码如下:

functionName("First_item") + 
functionName("Second_item") + 
functionName("Third_item") + 
Run Code Online (Sandbox Code Playgroud)

对于这样的事情:

functionName("First_item", "Second_item", "Third_item");
Run Code Online (Sandbox Code Playgroud)

该函数将针对列表中的每个项运行,因此结果相同但代码更加优雅和可维护.

笔记:

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

  1. Amit Joki的回答请注意我可以使用参数.当我实现代码时,修改后的函数(JSFiddle)只返回output第一个参数/ item 的字符串.

  2. Vanice的回答指出了最终的解决方案.

    • 通过连接(连接)outputfor循环中的字符串(使用+=),从所有参数/项的输出中创建一个字符串.
    • 通过放置returnfor循环的外部来返回连接的输出.

工作解决方案(JSFiddle).


谢谢

非常感谢大家的时间和帮助.对此,我真的非常感激!

doc*_*ore 5

利用Javascript的Prototype OOP:您可以将每个函数添加到Array本身,因此代码中的每个数组都会自动拥有每个函数.

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

用法:

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);
});
Run Code Online (Sandbox Code Playgroud)

注意事项:

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

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

您应该认真考虑的图书馆:

lodash: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)
Run Code Online (Sandbox Code Playgroud)

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

_.each([1, 2, 3], alert);
=> alerts each number in turn...
Run Code Online (Sandbox Code Playgroud)