JavaScript应用技巧集合.docx
《JavaScript应用技巧集合.docx》由会员分享,可在线阅读,更多相关《JavaScript应用技巧集合.docx(24页珍藏版)》请在冰点文库上搜索。
JavaScript应用技巧集合
JavaScript应用技巧集合(转载)
前段时间我曾经对JavaScript中的应用技巧进行了收集和总结,形成了以下几篇文章:
∙JavaScripttipsandtricks-1
∙JavaScripttipsandtricks-2
∙JavaScripttipsandtricks-3
∙JavaScripttipsandtricks-4
∙JavaScripttipsandtricks-5
这里我将会对这些应用技巧进行集中描述,如果你觉得遗漏了一些好用的应用技巧,也请在留言中提出,我会及时更新到这篇文章中的。
∙转化为Boolean类型
所有JavaScript中的值都能隐式的转化为Boolean类型,比如:
viewsource
print?
1
0==false;//true
2
1==true;//true
3
''==false//true
4
null==false//true
但是这些值都不是Boolean类型。
因此当我们使用三个等于号进行比较时:
viewsource
print?
1
0===false;//false
2
1===true;//false
3
''===false//false
4
null===false//false
现在的问题是如何将其他类型转化为Boolean类型:
viewsource
print?
1
!
!
0===false;//true
2
!
!
1===true;//true
3
!
!
''===false//true
4
!
!
null===false//true
∙为参数赋初值
JavaScript中没有重载的概念,但是JavaScript中函数的参数都是可选的,如果调用时少写了一个参数,将会被undefined所代替。
viewsource
print?
1
functionplus(base,added){
2
returnbase+added;
3
}
4
plus
(2);//NaN
在这个例子中,plus
(2)和plus(2,undefined)是等价的,2+undefined的结果是NaN。
现在的问题是,如果没有传递第二个参数,如何为它赋初值呢?
viewsource
print?
1
functionplus(base,added){
2
added=added||1;
3
returnbase+added;
4
}
5
plus
(2);//3
6
plus(2,2);//4
有网友提到plus(2,0)=3;的确是这样的,看来这个地方还要做一些特殊处理:
viewsource
print?
1
functionplus(base,added){
2
added=added||(added===0?
0:
1);
3
returnbase+added;
4
}
∙阻止别人在Iframe中加载你的页面
如果你的网站变得非常有人气的时候,就有很多网站想链接到你的网站,甚至想把你的网页通过IFrame嵌入它自己的网页。
这样就不好玩了,那么如何来阻止这样行为呢?
viewsource
print?
1
if(top!
==window){
2
top.location.href=window.location.href;
3
}
这段代码应该放在你每个页面的head中,如果你想知道现实中有没人在用,看看baidu的博客你就知道了。
∙字符串替换
String.prototype.replace函数经常会让那些非常熟悉C#或者Java的程序员感到迷惑。
比如:
viewsource
print?
1
'Helloworld,helloworld'.replace('world','JavaScript');
2
//Theresultis"HelloJavaScript,helloworld"
replace函数的第一个参数是正则表达式。
如果你传递一个字符串到第一个参数,则只有第一个找到的匹配字符串被替换。
为了解决这个问题,我们可以使用正则表达式:
viewsource
print?
1
'Helloworld,helloworld'.replace(/world/g,'JavaScript');
2
//Theresultis"HelloJavaScript,helloJavaScript"
我们还可以指定在替换时忽略大小写:
viewsource
print?
1
'Helloworld,helloworld'.replace(/hello/gi,'Hi');
2
//Theresultis"Hiworld,Hiworld"
∙将arguments转化为数组
函数中的预定义变量arguments并非一个真正的数组,而是一个类似数组的对象。
它具有length属性,但是没有slice,push,sort等函数,那么如何使arguments具有这些数组才有的函数呢?
也就是说如何使arguments变成一个真正的数组呢?
viewsource
print?
1
functionargs(){
2
return[].slice.call(arguments,0);
3
}
4
args(2,5,8);//[2,5,8]
∙为parseInt函数指定第二个参数
parseInt用来将字符串转化为整形的数字,语法为:
viewsource
print?
1
parseInt(str,[radix])
其中第二个参数是可选的,用来指定第一个参数是几进制的。
如果没有传递第二个参数,则按照如下规则:
->如果str以0x开头,则认为是16进制。
->如果str以0开头,则认为是8进制。
->否则,认为是10进制。
因此如下的代码将会让人很迷惑,如果你不知道这些规则:
viewsource
print?
1
parseInt('08');//0
2
parseInt('08',10);//8
所以,安全起见一定要为parseInt指定第二个参数。
∙从数组中删除一个元素
或许我们可以通过delete来做到:
viewsource
print?
1
vararr=[1,2,3,4,5];
2
deletearr[1];
3
arr;//[1,undefined,3,4,5]
可以看到,delete并不能真正的删除数组中的一个元素。
删除的元素会被undefined取代,数组的长度并没有变化。
事实上,我们可以通过Array.prototype中的splice函数来删除数组中的元素,如下所示:
viewsource
print?
1
vararr=[1,2,3,4,5];
2
arr.splice(1,1);
3
arr;//[1,3,4,5]
∙函数也是对象
在JavaScript中函数也是对象,因为我们可以为函数添加属性。
比如:
viewsource
print?
1
functionadd(){
2
returnadd.count++;
3
}
4
add.count=0;
5
add(); //0
6
add(); //1
7
add(); //2
我们为函数add添加了count属性,用来记录此函数被调用的次数。
当然这可以通过更优雅的方式来实现:
viewsource
print?
1
functionadd(){
2
if(!
arguments.callee.count){
3
arguments.callee.count=0;
4
}
5
returnarguments.callee.count++;
6
}
7
add(); //0
8
add(); //1
9
add(); //2
arguments.callee指向当前正在运行的函数。
∙数组中的最大值
如何在全是数字的数组中找到最大值,我们可以简单的通过循环来完成:
viewsource
print?
1
vararr=[2,3,45,12,8];
2
varmax=arr[0];
3
for(variinarr){
4
if(arr[i]>max){
5
max=arr[i];
6
}
7
}
8
max;//45
有没有其他方法?
我们都知道JavaScript中有一个Math对象进行数字的处理:
viewsource
print?
1
Math.max(2,3,45,12,8);//45
然后,我们可以这样来找到数组中最大值:
viewsource
print?
1
vararr=[2,3,45,12,8];
2
Math.max.apply(null,arr);//45
∙为IE添加console.log函数
在Firefox下并有Firebug的支持下,我们经常使用console.log来在控制台记录一些信息。
但是这种做法在IE下会阻止JavaScript的执行(在Firefox下没有启用Firebug情况下也是一样),因为此时根本没有console对象存在。
我们可以通过如下小技巧来防止这样情况的发生:
viewsource
print?
1
if(typeof(console)==='undefined'){
2
window.console={
3
log:
function(msg){
4
alert(msg);
5
}
6
};
7
}
8
console.log('debuginfo.');
∙undefined是JavaScript中保留关键字么?
看起来像是的,但实际上undefined并不是JavaScript中的关键字:
viewsource
print?
1
varundefined='Hello';
2
undefined;//'Hello'
这段代码可能会让你感到很奇怪,不过它的确能够正常运行,undefined只是JavaScript中一个预定义的变量而已。
注:
在JavaScript程序中,千万不要这样做,这个技巧只是告诉你有这么一回事而已。
∙判断一个变量是否为undefined
两种情况下,一个变量为undefined:
1.声明了变量,但是没有赋值
viewsource
print?
1
varname;
2
name===undefined;//true
2.从来没有声明过此变量
viewsource
print?
1
name2===undefined;//error–name2isnotdefined
在第二种情况下,会有一个错误被抛出,那么如果判断一个变量是否为undefined而不产生错误呢?
下面提供了一种通用的方法:
viewsource
print?
1
typeof(name2)===‘undefined’;//true
∙预加载图片
预加载图片就是加载页面上不存在的图片,以便以后使用JavaScript把它们快速显示出来。
比如你想在鼠标移动到某个图片上时显示另一张图片:
viewsource
print?
1
varimg=newImage();
2
img.src="clock2.gif";
viewsource
print?
1
2
onmouseover="this.src='clock2.gif';"
3
onmouseout="this.src=clock.gif';"/>
那么,如何加载一组图片呢?
考虑如下代码:
viewsource
print?
1
varsource=['img1.gif','img2.gif'];
2
varimg=newImage();
3
for(vari=0;i4
img.src=source[i];
5
}
实际上,这段代码只能预加载最后的一张图片,因为其他的图片根本没有时间来预加载在循环到来的时候。
因此正确的写法应该是:
viewsource
print?
1
varsource=['img1.gif','img2.gif'];
2
for(vari=0;i3
varimg=newImage();
4
img.src=source[i];
5
}
∙闭包(closure)
闭包指的是函数内的局部变量,当函数返回时此变量依然可用。
当你在函数内部定义另外一个函数时,你就创建了一个闭包,一个著名的例子:
viewsource
print?
1
functionadd(i){
2
returnfunction(){
3
return++i;
4
};
5
}
6
add
(2).toString();//"function(){return++i;}"
7
add
(2)();//3
add
(2)是一个函数,它可能获取外部函数的局部变量i。
参考文章
∙私有变量
我们经常使用命名规范来标示一个变量是否为私有变量(最常用来标示):
viewsource
print?
1
varperson={
2
_name:
'',
3
getName:
function(){
4
returnthis._name||'notdefined';
5
}
6
};
7
person.getName();//"notdefined"
下划线前缀用来作为私有变量的约定,但是其他开发人员仍然可以调用此私有变量:
viewsource
print?
1
person._name;//""
那么,如何在JavaScript中创建一个真正的私有变量呢?
主要技巧是使用匿名函数(anonymousfunction)和闭包(closure)。
viewsource
print?
01
varperson={};
02
(function(){
03
var_name='';
04
person.getName=function(){
05
return_name||'notdefined';
06
}
07
})();
08
09
person.getName();//"notdefined"
10
typeof(person._name);//"undefined"
∙JavaScript没有块级上下文(Scope)
JavaScript中块级代码没有上下文,实际上只有函数有自己的上下文。
viewsource
print?
1
for(vari=0;i<2;i++){
2
3
}
4
i; //2
如果想创建一个上下文,可以使用自执行的匿名函数:
viewsource
print?
1
(function(){
2
for(vari=0;i<2;i++){
3
4
}
5
})();
6
typeof(i)==='undefined'; //true
∙怪异的NaN
NaN用来表示一个值不是数字。
NaN在JavaScript中行为很怪异,是因为那NaN和任何值都不相等(包括它自己)。
viewsource
print?
1
NaN===NaN;//false
因为下面的代码可能会让一些人抓狂:
viewsource
print?
1
parseInt('hello',10);//NaN
2
parseInt('hello',10)==NaN;//false
3
parseInt('hello',10)===NaN;//false
那么如何来检查一个值是否NaN?
可以使用window.isNaN来判断:
viewsource
print?
1
isNaN(parseInt('hello',10));//true
∙真值和假值
JavaScript中所有值都能隐式地转化为Boolean类型。
在条件判断中,下面这些值会自动转化为false:
null,undefined,NaN,0,‘’,false
因此,不需要做如下复杂的判断:
viewsource
print?
1
if(obj===undefined||obj===null){
2
}
而只需要这样做就行了:
viewsource
print?
1
if(!
obj){
2
3
}
∙修改arguments
比如,添加一个值到arguments中:
viewsource
print?
1
functionadd(){
2
arguments.push('newvalue');
3
}
4
add();//error-arguments.pushisnotafunction
这样会出错,因为arguments不是一个真正的数组,没有push方法。
解决办法:
viewsource
print?
1
functionadd(){
2
Array.prototype.push.call(arguments,'newvalue');
3
returnarguments;
4
}
5
add()[0];//"newvalue"
∙Boolean和newBoolean
我们可以把Boolean看做是一个函数,用来产生Boolean类型的值(Literal):
viewsource
print?
1
Boolean(false)===false;//true
2
Boolean('')===false;//true
所以,Boolean(0)和!
!
0是等价的。
我们也可以把Boolean看做是一个构造函数,通过new来创建一个Boolean类型的对象:
viewsource
print?
1
newBoolean(false)===false;//false
2
newBoolean(false)==false;//true
3
typeof(newBoolean(false));//"object"
4
typeof(Boolean(false));//"boolean"
∙快速字符串连接
我们经常使用+将较短的字符串连接为一个长字符串,这在大部分的情况下是没问题的。
但是如果有大量的字符串需要连接,这种做法将会遇到性能问题,尤其是在IE下。
viewsource
print?
1
varstartTime=newDate();
2
varstr='';
3
for(vari=0;i<50000;i++){
4
str+=i;
5
}
6
alert(newDate()-startTime); //F