简体   繁体   English

使用JavaScript中的多个参数多次调用一个函数

[英]Call a function multiple times with more than one argument in JavaScript

Let's say I have this function 假设我有这个功能

function myFunction(a, b, c) {
    ... code here ...
}

Now I want to call it multiple times with several different arguments each time: 现在,我想多次调用它,每次使用几个不同的参数:

myFunction('sky', 'blue', 'air');
myFunction('tree', 'green', 'leaf');
myFunction('sun', 'yellow', 'light');
myFunction('fire', 'orange', 'heat');
myFunction('night', 'black', 'cold');

How can I merge all those calls in just one? 如何将所有这些呼叫合并为一个?

I know how to do it with iterations or forEach when there is just one argument, but I can't figure out how to do it with various non-numerical arguments. 当只有一个参数时,我知道如何使用迭代或forEach做到这一点,但我无法弄清楚如何使用各种非数值参数来做到这一点。

Unless you change myFunction , you can't call it once and have it magically act as though it had been called five times. 除非您更改myFunction ,否则您将无法调用它一次并使它具有被调用五次的神奇效果。

You can code a single call in a loop, though, if the information you're for the arguments using is stored elsewhere. 但是,如果您要使用的参数信息存储在其他位置,则可以在循环中编写单个调用的代码

For instance, if we assume an array of objets: 例如,如果我们假设一个objets数组:

var data = [
    {a: 'sky', b: 'blue', c: 'air'},
    {a: 'tree', b: 'green', c: 'leaf'},
    {a: 'sun', b: 'yellow', c: 'light'},
    {a: 'fire', b: 'orange', c: 'heat'},
    {a: 'night', b: 'black', c: 'cold'}
]:

then 然后

data.forEach(function(entry) {
    myFunction(entry.a, entry.b, entry.c);
});

Or if it's an array of arrays, we can use the nifty Function#apply function: 或者,如果它是一个数组数组,我们可以使用漂亮的Function#apply函数:

var data = [
    ['sky', 'blue', 'air'],
    ['tree', 'green', 'leaf'],
    ['sun', 'yellow', 'light'],
    ['fire', 'orange', 'heat'],
    ['night', 'black', 'cold']
]:

then: 然后:

data.forEach(function(entry) {
    myFunction.apply(null, entry);
});

You seem to be looking for apply 您似乎正在寻找apply

var values = [
    ['sky', 'blue', 'air'],
    ['tree', 'green', 'leaf'],
    ['sun', 'yellow', 'light'],
    ['fire', 'orange', 'heat'],
    ['night', 'black', 'cold']
];
values.forEach(function(args) { myFunction.apply(null, args); })

or spread syntax in ES6: 或在ES6中扩展语法

for (const args of values) myFunction(...args);

lets suppose you already have an array with all the values: 假设您已经有一个包含所有值的数组:

 var colors = ['sky', 'blue', 'air', 'tree', 'green', 'leaf', 'sun', 'yellow', 'light', 'fire', 'orange', 'heat', 'night', 'black', 'cold']; while(colors.length > 0){ myFunction.apply(this, colors.splice(0,3)); //call the function with chunks of 3 elements } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM