簡體   English   中英

如何在數組中包含參數時調用函數

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

假設我們有一個功能

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()

f.apply(window, args);

這將適用於第二個參數位置中任何類似數組的對象。

它調用函數f ,並設置你傳遞作為其第一個參數this(在這里我只是用window后,分配第二個參數作為單獨的函數的自變量的成員。

結果就好像你這樣做了:

f(5, 'string', 12);

.call()Function.prototype.apply方法相對應。 除了單獨傳遞參數之外, .call()方法完全相同。

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

這樣做的目的是調用正常的函數,但手動設置this值。

使用.apply() 第二個參數允許您指定要嘗試調用的函數的參數數組。 第一個參數是值this你在函數的情況下想要的。

所以在你的情況下它將是:

f.apply(null, args);

要么

f.apply(window, args);

如果你想this的背景下fwindow對象。

這取決於你的需求(當然)

如果元素是同質的

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方法)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM