2013-01-06 19 views
4

我願做這樣的事情:更改的第一個參數的函數

function start(){ 
    // Change the first argument in the argument list 
    arguments[0] = '<h1>' + arguments[0] + '</h1>'; 

    // Call log with the new arguments 
    // But outputs: TypeError: Illegal invocation 
    log.apply(this, arguments); 
} 

function log(){ 
    console.log(arguments); 
    // should output -> ['<h1>hello<h1>', 'world', '!'] 
} 


start('hello', 'world', '!'); 
+0

注意'print'是已經是一個內置的功能。 –

+0

@Waleed Khan謝謝,我編輯了這個問題。 – Adam

+2

當你傳遞給apply函數時,'arguments'不是一個數組可能會導致一個問題:_The arguments對象不是一個Array。它類似於一個數組,但沒有任何數組屬性,除了length._ - https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Functions_and_function_scope/arguments – banzomaikaka

回答

5

你的代碼實際工作(我只是在Firefox測試,最新的版本)。

不過,我可以想像,傳遞的價值Function.prototype.apply時,一些實現可能有問題arguments對象。因此,嘗試:

function start(){ 
    var args = Array.prototype.slice.call(arguments); 
    args[0] = '<h1>' + args[0] + '</h1>'; 

    log.apply(this, args); 
} 

通過對arguments -object調用Array.prototype.slice,我們創建了一個 「真正」 的EcmaScript 陣列,我們可能需要作爲第二個參數爲.apply()

+0

你是對的我的代碼作品!在我的生產代碼中,我試圖在'console.log'上使用apply,這就是爲什麼它不起作用。我只需要將上下文更改爲控制檯。但無論如何,你的答案是有幫助的,我只是意識到,我可以使用簡單的數組與應用:) – Adam

相關問題