簡體   English   中英

JavaScript改變函數參數並用於function.apply

[英]JavaScript alter function arguments and use for function.apply

我定義了console.log的替代品,它基本上將一個全局int變量添加到日志的開頭。

在函數中,我向后迭代arguments數組,直到index等於1並向前移動每個元素一個。

然后我在索引1處添加全局int值,並在索引0處更改格式字符串以尊重新參數。

執行此操作時, console.log使用新的格式字符串和參數,但似乎忽略了第二個 - 最初的第一格式參數。

所以我創建了一些測試函數來比較它們的輸出行為:

var globalInt = 25;
function log() {
    if (arguments.length > 0 && arguments[0].length > 0) {
        var keys = Object.keys(arguments);

        for (var i = keys.length - 1; i > 0; i--) {
            arguments[parseInt(keys[i]) + 1] = arguments[keys[i]];
        }

        arguments['0'] = '%d: ' + arguments['0'];
        arguments['1'] = globalInt;
    }

    console.log('  %s', JSON.stringify(arguments));
    console.log.apply(console.log, arguments);
}
function log_t1() {
    console.log('  %s', JSON.stringify(arguments));
    console.log.apply(console.log, arguments);
}
function log_t2() {
    if (arguments.length > 0 && arguments[0].length > 0) {
        arguments[0] = '%d: ' + arguments[0];
    }

    console.log('  %s', JSON.stringify(arguments));
    console.log.apply(console.log, arguments);
}

log('test "%s"', 'hello world');

log_t1('%d: test "%s"', globalInt, 'hello world');
log_t2('test "%s"', globalInt, 'hello world');


>> 
  {"0":"%d: test \"%s\"","1":25,"2":"hello world"}
25: test "%s"
  {"0":"%d: test \"%s\"","1":25,"2":"hello world"}
25: test "hello world"
  {"0":"%d: test \"%s\"","1":25,"2":"hello world"}
25: test "hello world"

比較這些函數,它們的調用,它們的輸出,尤其是相同的JSON打印,我真的很想知道第一個結果。

有人可以在代碼中看到任何問題或可以確認此行為嗎?

您沒有更改arguments對象的length屬性。 arguments對象不是一個簡單的數組,它是不同的東西,並且在過度索引時不會改變它自己的長度屬性。

我建議你先將arguments對象轉換為數組,並在循環中使用數組方法:

var globalInt = 25;
...
function log() {
    var args = Array.prototype.slice.call(arguments, 0);
    if (args.length > 0 && args[0].length > 0) {
        args = ['%d:  ' + args[0], globalInt].concat(args.slice(1));
    }

    console.log('  %s', JSON.stringify(args));
    console.log.apply(console, args);
}

暫無
暫無

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

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