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

JavaScript使用技巧集合一

2010-02-23 22:59 387 查看
转化为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
function
plus(base,added){
2
return
base+added;
3
}
4
plus(2);
//NaN
在这个例子中,plus(2)和plus(2,undefined)是等价的,2+undefined的结果是NaN。
现在的问题是,如果没有传递第二个参数,如何为它赋初值呢?

viewsource

print?

1
function
plus(base,added){
2
added=added||1;
3
return
base+added;
4
}
5
plus(2);
//3
6
plus(2,2);
//4
有网友提到plus(2,0)=3;的确是这样的,看来这个地方还要做一些特殊处理:

viewsource

print?

1
function
plus(base,added){
2
added=added||(added===0?0:1);
3
return
base+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
function
args(){
2
return
[].slice.call(arguments,0);
3
}
4

args(2,5,8);
//[2,5,8]

转自:/article/4676633.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: