JavaScript 改变函数参数并用于 function.apply

JavaScript alter function arguments and use for function.apply

我定义了 console.log 的替代品,它基本上将全局 int 变量添加到日志的开头。

在函数中,我向后迭代 arguments 数组直到索引等于 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 对象不是一个简单的数组,它是不同的东西,并且在过度索引时不会改变它自己的长度 属性。

我建议您先将参数对象转换为数组,并优先使用数组方法而不是循环:

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);
}