当我们在数组中有函数的参数时,如何调用函数

How to call a function when we have its arguments in an array

本文关键字:函数 何调用 调用 参数 我们 数组      更新时间:2023-09-26

假设我们有一个函数

f = function(a, b, c){
    // do something important
}

和一个包含参数的数组

var args = [5, 'string', 12] // just any values

显然,我可以像这样调用我的函数:

f(args[0], args[1], args[2])

这真的不优雅,我正在寻找更好的方法来实现这一目标。感谢您的建议。

你正在寻找 Function.apply()

f.apply(window, args); // pass something other than null to set 'this' within the call

使用 .apply() .第二个参数允许您为尝试调用的函数指定参数数组。第一个参数是函数上下文中所需的this值。

所以在你的情况下,它会是:

f.apply(null, args);

f.apply(window, args);

如果您希望f上下文中的this成为window对象。

使用 .apply() .

f.apply(window, args);

这将适用于第二个参数位置的任何类似数组的对象。

它调用函数 f ,并将您传递的第一个参数设置为其this(这里我只是使用了 window),并将第二个参数的成员作为单独的参数分发给函数。

结果就像您已经这样做了一样:

f(5, 'string', 12);

Function.prototype.apply方法有一个对应的方法称为 .call() ..call() 方法完全相同,只是单独传递参数。

f.call(window, 5, 'string, 12);

这样做的目的是像正常一样调用函数,但手动设置this值。

这取决于您的需求(当然)

如果元素是同质的

var sum = function(numbers) {
   // do some calculations
}
var randomees = [5, 6, 12]
var total = sum(randomees);

如果不是,它们应该有某种描述。 即,如果您正在定义选项或参数,那么您应该考虑这一点

var parameters = {
    size:13,
    shipped:true,
    description:"Laptop"
}
var displayLaptop = function(characteristics) {
    console.log(characteristics.size)
}

(甚至玩一些jQuery.extend ish方法)