ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

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

2019-11-19 19:34:12  阅读:179  来源: 互联网

标签:console-log function-calls javascript


我定义了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对象不是简单的数组,它有所不同,并且在过度索引时不会更改其自身的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);
}

标签:console-log,function-calls,javascript
来源: https://codeday.me/bug/20191119/2038676.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有