gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 01:16:26 25 4
gpt4 key购买 nike

我有一个用条件包装 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com