您的位置:首页 > Web前端 > JavaScript

javascript tips and snippets

2015-11-25 22:08 603 查看

数字化的Date

js中,Date是内置的一种数据类型,虽然直接输出的date格式适合人们阅读,但是对于机器程序来说却有些不方便:

var now=new Date();
console.log(now);//Wed Nov 25 2015 22:02:17 GMT+0800 (中国标准时间)


怎么转换为便于js程序来操作的形式呢?很简单只要在new关键字前面加上一个+即可:

var now=+new Date();
console.log(now);//1448460291345


javascript Errors:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error

try {
foo.bar();
} catch (e) {
if (e instanceof EvalError) {
alert(e.name + ': ' + e.message);
} else if (e instanceof RangeError) {
alert(e.name + ': ' + e.message);
} else if (e instanceof InternalError) {
alert(e.name + ': ' + e.message);
}else if (e instanceof ReferenceError) {
alert(e.name + ': ' + e.message);
}else if (e instanceof SyntaxError) {
alert(e.name + ': ' + e.message);
}else if (e instanceof TypeError) {
alert(e.name + ': ' + e.message);
}else if (e instanceof URIError) {
alert(e.name + ': ' + e.message);
}
// ... etc
}


Javascript小数点问题

由于javascript使用浮点数来运算小数,而小数总归会有一定的精确度,所以往往出现一些比较怪异的问题:

console.log(0.1+0.2);//0.30000000000000004
console.log((0.1+0.2).toFixed(2));//0.30
(0.1+0.2)==0.3 //false!!!!
(0.1+0.2).toFixed(1)==0.3 //true!!!
(0.1+0.2).toFixed(2)===0.3 //flase!!! 原因是toFixed(2)调用后实际上返回的是"0.30"


在上面的代码,由于toFixed将返回一个字符串,所以使用===来比较,则返回false;再看下面的代码:

function tax(price,percent){
return parseFloat((price*percent/100).toFixed(2));
}
var myprice = 9;
var taxpercent =70;
var total = myprice+tax(myprice,taxpercent);
console.log(total.toFixed(2)); //"15.30"


javascript hoisting

<!DOCTYPE html>
<html>
<body>

<p id="demo"></p>

<script>
var x = 5;  // Initialize x

elem = document.getElementById("demo");            // Find an element
elem.innerHTML = "x is " + x + " and y is " + y;    // Display x and y==> x is 5 and y is undefined,虽然y是declared了(due to hoisting),但是却没有defination未定义

var y = 7;  // Initialize y
</script>

</body>
</html>


modula Pattern

var ARMORY =(function(){
var weaponList = [*list of weapon objects*];
var armorList = [*list of armor objects*];

var removeWeapon = function(){};
var replaceWeapon = function(){};
var removeArmor = function(){};
var replaceArmor = function(){};

return {
makeWeaponRequest: function(){};
makeArmorRequest: function(){};
};

})();
ARMORY.makeWeaponRequest('Excalibur');


上面这段代码中,使用IIFE调用后返回一个global object ARMORY作为namespace,暴露两个public函数公外部调用,内部的local data都已经被封装起来,

通过ARMORY.makeWeaponRequest()函数调用,来通过private函数removeWeapon又去访问namespace的local variable weapList,删除相应武器数据后,可能返回一个weapon列表对象的copy到ARMORY.makeWeaponRequest的scope中去使用。

Import Globals into IIFE

在上面的module pattern中,如果需要访问一个全局变量,比如我们添加一个指示是否正在战争游戏的flag,在makeWeaponRequest函数中,我们根据这个flag来做特定的动作,那么可行的方法是将wartime这个flag作为IIFE的参数传入:

var wartime = true;
var ARMORY =(function(war){
var weaponList = [*list of weapon objects*];
var armorList = [*list of armor objects*];

var removeWeapon = function(){};
var replaceWeapon = function(){};
var removeArmor = function(){};
var replaceArmor = function(){};

return {
makeWeaponRequest: function(){
if(war) //let civilians have weaponry

};
makeArmorRequest: function(){};
};

})(wartime);
ARMORY.makeWeaponRequest('Excalibur');


在上面这个pattern中,需要注意的是wartime作为参数传入了IIFE虽然意味着IIFE中能够方便的访问到wartime的数据拷贝,但是如果外部的环境发生变化了,后续再调用makeWeaponRequest时,无法感知!@!原因是war这里是wartime的一个copy,并不是直接引用!

当然,如果希望内部和外部完全同步,有一个可行的方法是,将wartime声明为一个object或者array,在IIFE内部通过 object.property,array[index]方式来读或者写就可以实现内外完全同步了!看下面的简单说明:

function replace(ref) {
ref = {};           // this code does _not_ affect the object passed
}

function update(ref) {
ref.key = 'newvalue';  // this code _does_ affect the _contents_ of the object
}

var a = { key: 'value' };
replace(a);  // a still has its original value - it's unmodfied
update(a);   // the _contents_ of 'a' are changed


文字盒翻滚效果

var wordBox = $("#theWords");
var timer;

timer = setTimeout(function(){

var argCallee = arguments.callee;

var fSpan = $("#theWords span:first");

fSpan.animate({
marginTop:-20
},500,function(){
wordBox.append(fSpan);
fSpan.css("margin-top","0");
timer = setTimeout(argCallee,3000);
});

},3000);
html:
<div id="theWords" class="theScrollword">      <span style="margin-top: 0px;">不怕做不到只怕想不到。</span><span style="margin-top: 0px;">学而不思则罔!</span><span style="margin-top: 0px;">思而不学则殆 </span><span style="margin-top: 0px;">我听我忘,我看我会,我做我懂 </span><span style="margin-top: 0px;">做个有价值的人。</span></div>
css:
.theScrollword {
height: 20px;
overflow: hidden;
position: relative;
margin: 20px 0 0;
padding: 0 0 0 40px;
float: left;
display: inline;
}
.container .toparea .notice span {
text-align: left;
color: #fffeff;
font-size: 14px;
display: block;
}


上面一段代码的原理是使用jquery的animate函数对第一个span的margin-top属性来做动画,并且不断将第一个span移动到最后去

jquery document ready and window load

我们知道javascript在操作一个页面的元素时,必须保证document is "ready"。 jQuery侦测readiness状态。在$(document).ready()函数中的代码只有在页面的Document Object Model(DOM)完全就绪后才会被执行(而对于未定义在ready handler中的javascript代码则基本上会在DOM完全构建完成之前运行!!!)。而在$(window).load(function(){...})中的代码则只有整个page的资源(images,css,iframes)都加载完成(或者timeout failure)后才被运行,而不是DOM一就绪就运行;

DOM就绪发生在HTML Document被浏览器接收(注意对应的JS也被加载运行了!!),并且解析成对应的DOM数后发生!。看看下面的示例代码:

<html>
<head>
<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
$( document ).ready(function() {
console.log( "document loaded" );
});

$( window ).load(function() {
console.log( "window loaded" );
});
</script>
</head>
<body>
<img src="http://xx.yy.com/build/images/internet.jpg" />
<iframe src="http://techcrunch.com"></iframe>
</body>
</html>


上面的代码将首先打出“document loaded”,随后在img,iframe全部加载完成后,打印出"window loaded"

列出所有全局空间的对象

有时我们希望看到在我们的页面上有哪些可以操作的全局对象,通过Object.keys(window)就可以轻松实现。更进一步,我们希望打印出对象,并且方便检视,则可以使用下面的代码:

(function ()
{
var keys=Object.keys( window );
for (var i in keys)
{
if (typeof window[keys[i]] != 'function')
console.log(keys[i], window[keys[i]]);
}
})();


函数柯里化充分理解闭包,返回函数的概念

function add(value) {
var helper = function(next) {
console.log("value is: "+ value + "--line 481" );
value = typeof(value)==="undefined"?next:value+next;
console.log("value is: " +value + "--line 483");
return helper;
}
helper.valueOf = function() {
console.log("valueOf is called at 488");
return value;
}
return helper;
}
console.log(add(2)(3)(5)(7));


value is: 2--line 481
value is: 5--line 483
value is: 5--line 481
value is: 10--line 483
value is: 10--line 481
value is: 17--line 483
jstext.html:495 17
valueOf is called at 488

注意:valueOf是console.log(returnHelper)时js引擎自动会调用returnHelper.valueOf方法的~~~!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: