javascript - 将多个参数传递给 console.log

标签 javascript console firebug developer-tools

我有一个用条件包装 console.log 的实用函数,所以我们只在开发环境中调用 console.log 并且 console.log 存在:

/* Console log if environment has debug true or #debug initially passed in URL */
metro.conlog = (function () {
    return function (message) {
        if ((metro.siteData.debug || metro.hashOptions.hasOwnProperty('debug')) && window.console && message) {
            console.log(message);
        }
    };
}());

这对于普通的控制台日志非常有效。但我最近发现了将多个参数传递给 console.log 的乐趣:它允许您在控制台日志前加上字符串前缀,因此 console.log('DEBUG', object) 输出字符串加上一个可以检查其属性的可扩展对象。我怎样才能改变我的 conlog 功能来做到这一点?我试过像这样注销所有参数:

metro.conlog = (function () {
    return function (message) {
        if ((metro.siteData.debug || metro.hashOptions.hasOwnProperty('debug')) && window.console && message) {
            console.log(arguments);
        }
    };
}());

但这会将参数输出为数组,而不是使用 console.log 得到的整齐的一行。您可以在此屏幕截图中看到不同之处:

enter image description here

谁能告诉我如何重现原始日志输出?

最佳答案

当然可以,this是一个演示,说明如何准确地执行您需要的操作,并添加了额外的选项。

代码如下:

var mylog = (function () {
    return {
        log: function() {
            var args = Array.prototype.slice.call(arguments);
            console.log.apply(console, args);
        },
        warn: function() {
            var args = Array.prototype.slice.call(arguments);
            console.warn.apply(console, args);
        },
        error: function() {
            var args = Array.prototype.slice.call(arguments);
            console.error.apply(console, args);
        }
    }
}());

var name = "Alex";
var arr = [1, 2, 3];
var obj = { a:1, b:2, c:3 };
var hello = function(msg){alert(msg);};
mylog.log("Name: ", name);
mylog.log("Window Debug: ", window);
mylog.error("Some error happened");
mylog.warn("Ahh... Warning", arr, obj);
mylog.log("more parameters: ", arr, obj, hello);

关于javascript - 将多个参数传递给 console.log,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18746440/

相关文章:

java - 清除控制台的方法?

javascript - 在 Firebug 插件中提取 CSS 代码

javascript - 如何使用JS在canvas上绘制人物的一部分?

javascript - Angular ui-router $位置

javascript - 普通 JavaScript ajaxStop()

javascript - Firebug 调试器忽略 setTimeout?如何测试?

jquery - 将元素显示为 block 的分页 - CSS Jquery

javascript - 是否可以防止隐藏的元素跳入焦点 View

c# - 在控制台应用程序中捕获鼠标滚轮事件

python - 在 Python 脚本中使用 print 语句的性能效果