我有一个实用程序函数,它使用一个条件包装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);
}
};
}());
这对普通的控制台日志非常有用。但是我最近发现了将多个参数传递给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获得的整齐行。您可以在此屏幕截图中看到差异:
有人能告诉我如何重现原始日志输出吗?
答案 0 :(得分:27)
当然你可以做到,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);
答案 1 :(得分:1)
尝试这样的事情
/* Console log if environment has debug true or #debug initially passed in URL */
metro.conlog = (function () {
return function (message, object) {
if ((metro.siteData.debug || metro.hashOptions.hasOwnProperty('debug')) && window.console && message) {
console.log(message, object);
}
};
}());
其中message
类似于“DEBUG”,object
是您要检查的任何对象。
如果您希望能够将任意数量的参数传递到console.log
,我建议使用arguments
变量。
/* Console log if environment has debug true or #debug initially passed in URL */
metro.conlog = (function () {
return function (message, object) {
if ((metro.siteData.debug || metro.hashOptions.hasOwnProperty('debug')) && window.console && message) {
console.log(arguments);
}
};
}());
正如我在评论中提到的,我不确定哪些浏览器完全支持这一点(我正在看你的IE)。
我已经测试并确认它适用于当前的Chrome,FireFox和Safari。