JavaScript修改函数参数和使用函数

JavaScript alter function arguments and use for function.apply

本文关键字:函数 参数 修改 JavaScript      更新时间:2023-09-26

我定义了一个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);
}