这个片段是从JavaScript Ninja的Secrets中剪下来的.
function log() {
try {
console.log.apply( console, arguments );
} catch(e) {
try {
opera.postError.apply( opera, arguments );
} catch(e){
alert( Array.prototype.join.call( arguments, " " ) );
}
}
}
Run Code Online (Sandbox Code Playgroud)
我为什么要使用apply console.log.apply(console, arguments)和console.log(arguments)?之间的区别是什么?
我正在尝试创建一个函数,可以格式化一个数字,最小小数位数为2,最大值为4.所以基本上如果我传入354545.33,我会回到354,545.33,如果我传入54433.6559943,我会回来54,433.6559.
function numberFormat(num){
num = num+"";
if (num.length > 0){
num = num.toString().replace(/\$|\,/g,'');
num = Math.floor(num * 10000) / 10000;
num += '';
x = num.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
else{
return num;
}
}
Run Code Online (Sandbox Code Playgroud) 浏览器和节点之间有什么区别?例如:
setName.js 在节点上:
var setName;
setName = function (name) {
return this.name = name;
};
setName("LuLu");
//LuLu
console.log(name);
//undefined
console.log(this.name);
Run Code Online (Sandbox Code Playgroud)
setName.html 在浏览器中:
<script>
var setName;
setName = function (name) {
return this.name = name;
};
setName("LuLu");
//LuLu
console.log(name);
//LuLu
console.log(this.name);
</script>
Run Code Online (Sandbox Code Playgroud)
第二个日志不同,为什么?
好吧,我是node.js的新学习者:当我尝试加载google.com,并在页面中执行脚本时,如下所示:
var zombie=require("zombie");
browser = new zombie.Browser({ debug: true })
browser.visit("http://www.google.com",function(err,_browser,status){
if(err){
throw(err.message);
}
})
Run Code Online (Sandbox Code Playgroud)
但得到错误:
28 Feb 16:06:40 - The onerror handler
on target
{ frames: [ [Circular] ],
contentWindow: [Circular],
window: [Circular],
…………………………
Run Code Online (Sandbox Code Playgroud)
我能做什么?
在"JavaScript the Good Parts"中,with被认为是javascript的一个不好的部分,但请看这个片段:
var foo={foof:function(){console.log(this)}}
var fuu={fuuf:function(){console.log(this)}}
with(foo){
console.log(this);
with(fuu){
console.log(this);
foof();
fuuf();
}
}
Run Code Online (Sandbox Code Playgroud)
是否with真的如此糟糕做法?with有时可以提供乐趣或优势,谁可以举个例子?