Javascript 将多个参数传递到console.log
我有一个实用程序函数,它用一个条件包装console.log,因此只有在开发环境中且console.log存在时,我们才调用console.log:Javascript 将多个参数传递到console.log,javascript,console,firebug,developer-tools,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.deb
/* 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前面加上字符串,因此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获得的整齐线条。您可以在此屏幕截图中看到不同之处:
有人能告诉我如何重现原始日志输出吗?试试这样的方法
/* 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中都能正常工作。当然你能做到,这是一个演示如何准确地完成你所需要的,并添加了额外的选项
代码如下:
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);
谢谢Justin-但是如果我通过metro.conlog('foo')和metro.conlog('foo',myObject,另一个对象,'bar'),这个解决方案可以工作吗?如果你想这样使用它的话。您可以只使用
console.log(参数)这将放置您为函数提供的所有参数。我不确定浏览器的兼容性。我知道它适用于chrome、firefox和safari。我将对我的答案进行编辑。如果要使用console.log.apply(console,arguments)Justin,我确实尝试了console.log(arguments),但它没有给我与普通console.log相同的结果。哈格巴德,这正是我需要的答案,谢谢!你想把它作为一个答案发布吗?有什么解决方案可以应用颜色并记录所有的参数吗?很好!感谢包含演示链接!:)