繁体   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