console.log 获取未指定数量的参数并将其内容转储到一行中.
有没有办法可以编写一个函数来传递直接传递给它的参数console.log来维护这种行为?例如:
function log(){
if(console){
/* code here */
}
}
Run Code Online (Sandbox Code Playgroud)
这与以下内容不同:
function log(){
if(console){
console.log(arguments);
}
}
Run Code Online (Sandbox Code Playgroud)
因为arguments是一个数组console.log并将转储该数组的内容.它也不会是:
function log(){
if(console){
for(i=0;i<arguments.length;console.log(arguments[i]),i++);
}
}
Run Code Online (Sandbox Code Playgroud)
因为那将打印不同行中的所有内容.重点是保持console.log行为,但通过代理功能log.
+ ---
我正在寻找一种解决方案,我将来可以应用于所有函数(为函数创建一个代理,保持参数的处理完好无损).如果不能这样做,我会接受一个console.log具体的答案.
Gab*_*oli 85
这应该做..
function log() {
if(typeof(console) !== 'undefined') {
console.log.apply(console, arguments);
}
}
Run Code Online (Sandbox Code Playgroud)
只需添加另一个选项(使用扩展运算符和其余参数 - 尽管arguments可以直接使用传播)
function log(...args) {
if(typeof(console) !== 'undefined') {
console.log(...args);
}
}
Run Code Online (Sandbox Code Playgroud)
html5boilerplate代码中有一个很好的例子,它以类似的方式包装console.log,以确保不会破坏任何不能识别它的浏览器.它还添加了历史记录并平滑了console.log实现中的任何差异.
它由Paul Irish开发,他在这里写了一篇文章.
我已粘贴下面的相关代码,这是项目中文件的链接:https://github.com/h5bp/html5-boilerplate/blob/master/js/plugins.js
// usage: log('inside coolFunc', this, arguments);
// paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
window.log = function(){
log.history = log.history || []; // store logs to an array for reference
log.history.push(arguments);
if(this.console) {
arguments.callee = arguments.callee.caller;
var newarr = [].slice.call(arguments);
(typeof console.log === 'object' ? log.apply.call(console.log, console, newarr) : console.log.apply(console, newarr));
}
};
// make it safe to use console.log always
(function(b){function c(){}for(var d="assert,count,debug,dir,dirxml,error,exception,group,groupCollapsed,groupEnd,info,log,timeStamp,profile,profileEnd,time,timeEnd,trace,warn".split(","),a;a=d.pop();){b[a]=b[a]||c}}((function(){try {console.log();return window.console;}catch(err){return window.console={};}})());
Run Code Online (Sandbox Code Playgroud)