将多个参数传递给console.log

And*_*lly 17 javascript console firebug developer-tools

我有一个实用程序函数,它用一个条件包装console.log,所以如果我们在dev环境中并且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);
        }
    };
}());
Run Code Online (Sandbox Code Playgroud)

这对于普通的控制台日志非常有效.但是我最近发现了向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);
        }
    };
}());
Run Code Online (Sandbox Code Playgroud)

但是这会将参数作为数组输出,而不是使用console.log获得的整齐线.您可以在此屏幕截图中看到差异:

在此输入图像描述

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

Idh*_*ian 30

当然你可以做到这一点,是一个如何做到你需要的演示,并添加了额外的选项.

代码如下:

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);
Run Code Online (Sandbox Code Playgroud)