在这篇文章中,作者将会向大家分享JavaScript开发的小技巧、最佳实践等非常实用的内容,不管你是前端开发者还是服务端开发者,都应该来看看这些小技巧,它们绝对会让你受益的。
文中所提供的代码片段都已经过最新版的Chrome 30测试,该浏览器使用V8 JavaScript引擎(V8 3.20.17.15)。
1.第一次给变量赋值时,别忘记var关键字
给一个未声明的变量赋值,该变量会被自动创建为全局变量,在JS开发中,应该避免使用全局变量。
2.使用===替换==
并且永远不要使用=或!=。
1
2
3
4
5
6
7
8
|
[10] === 10
// is false
[10] == 10
// is true
'10'
== 10
// is true
'10'
=== 10
// is false
[] == 0
// is true
[] === 0
// is false
''
==
false
// is true but true == "a" is false
''
===
false
// is false
|
3.使用分号来作为行终止字符
在行终止的地方使用分号是一个很好的习惯,即使开发人员忘记加分号,编译器也不会有任何提示,因为在大多数情况下,JavaScript解析器会自动加上。
4.创建构造函数
1
2
3
4
5
6
|
function
Person(firstName, <span id=
"5_nwp"
style=
"width: auto; height: auto; float: none;"
><a id=
"5_nwl"
style=
"text-decoration: none;"
href=
"http://cpro.baidu.com/cpro/ui/uijs.php?c=news&cf=1001&ch=0&di=128&fv=17&jk=b214e2f7e7d8a432&k=last&k0=last&kdi0=0&luki=3&n=10&p=baidu&q=06011078_cpr&rb=0&rs=1&seller_id=1&sid=32a4d8e7f7e214b2&ssp2=1&stid=0&t=tpclicked3_hc&tu=u1922429&u=http%3A%2F%2Fwww%2Eadmin10000%2Ecom%2Fdocument%2F3589%2Ehtml&urlid=0"
target=
"_blank"
mpid=
"5"
><span style=
"width: auto; height: auto; color: rgb(0, 0, 255); font-size: 14px; float: none;"
>last</span></a></span>Name){
t<span id=
"6_nwp"
style=
"width: auto; height: auto; float: none;"
><a id=
"6_nwl"
style=
"text-decoration: none;"
href=
"http://cpro.baidu.com/cpro/ui/uijs.php?c=news&cf=1001&ch=0&di=128&fv=17&jk=b214e2f7e7d8a432&k=his&k0=his&kdi0=0&luki=2&n=10&p=baidu&q=06011078_cpr&rb=0&rs=1&seller_id=1&sid=32a4d8e7f7e214b2&ssp2=1&stid=0&t=tpclicked3_hc&tu=u1922429&u=http%3A%2F%2Fwww%2Eadmin10000%2Ecom%2Fdocument%2F3589%2Ehtml&urlid=0"
target=
"_blank"
mpid=
"6"
><span style=
"width: auto; height: auto; color: rgb(0, 0, 255); font-size: 14px; float: none;"
>his</span></a></span>.firstName = firstName;
this
.lastName = lastName;
}
var
Saad =
new
Person(
"Saad"
,
"Mousliki"
);
|
5.应当小心使用typeof、instanceof和constructor
1
2
3
4
|
var
arr = [
"a"
,
"b"
,
"c"
];
typeof
arr;
// return "object"
arr
instanceof
Array
// true
arr.constructor();
//[]
|
6.创建一个Self-calling函数
这通常会被称为自我调用的匿名函数或立即调用函数表达式(LLFE)。当函数被创建的时候就会自动执行,好比下面这个:
1
2
3
4
5
6
7
|
(
function
(){
// some private code that will be executed automatically
})();
(
function
(a,b){
var
result = a+b;
return
result;
})(10,20)
|
7.给数组创建一个随机项
1
2
3
|
var
items = [12, 548 ,
'a'
, 2 , 5478 ,
'foo'
, 8852, ,
'Doe'
, 2145 , 119];
var
randomItem = items[Math.floor(Math.random() * items.length)];
|
8.在特定范围里获得一个随机数
下面这段代码非常通用,当你需要生成一个假的数据用来测试时,比如在最低工资和最高之前获取一个随机值。
1
|
var
x = Math.floor(Math.random() * (max - min + 1)) + min;
|
9.在数字0和最大数之间生成一组随机数
1
2
3
|
var
numbersArray = [] , max = 100;
for
(
var
i=1; numbersArray.push(i++) < max;);
// numbers = [0,1,2,3 ... 100]
|
10.生成一组随机的字母数字字符
1
2
3
4
5
6
|
function
generateRandomAlphaNum(len) {
var
rdmstring =
""
;
for
( ; rdmString.length < len; rdmString += Math.random().toString(36).substr(2));
return
rdmString.substr(0, len);
}
|
11.打乱数字数组
1
2
3
|
var
numbers = [5, 458 , 120 , -215 , 228 , 400 , 122205, -85411];
numbers = numbers.sort(
function
(){
return
Math.random() - 0.5});
/* the array numbers will be equal for example to [120, 5, 228, -215, 400, 458, -85411, 122205] */
|
12.字符串tim函数
trim函数可以删除字符串的空白字符,可以用在Java、C#、PHP等多门语言里。
1
|
String.prototype.trim =
function
(){
return
t<span id=
"2_nwp"
style=
"width: auto; height: auto; float: none;"
><a id=
"2_nwl"
style=
"text-decoration: none;"
href=
"http://cpro.baidu.com/cpro/ui/uijs.php?c=news&cf=1001&ch=0&di=128&fv=17&jk=b214e2f7e7d8a432&k=his&k0=his&kdi0=0&luki=2&n=10&p=baidu&q=06011078_cpr&rb=0&rs=1&seller_id=1&sid=32a4d8e7f7e214b2&ssp2=1&stid=0&t=tpclicked3_hc&tu=u1922429&u=http%3A%2F%2Fwww%2Eadmin10000%2Ecom%2Fdocument%2F3589%2Ehtml&urlid=0"
target=
"_blank"
mpid=
"2"
><span style=
"width: auto; height: auto; color: rgb(0, 0, 255); font-size: 14px; float: none;"
>his</span></a></span>.replace(/^\s+|\s+$/g,
""
);};
|
13.数组追加
1
2
3
4
5
|
var
array1 = [12 ,
"foo"
, {name
"Joe"
} , -2458];
var
array2 = [
"Doe"
, 555 , 100];
Array.prototype.push.apply(array1, array2);
/* array1 will be equal to [12 , "foo" , {name "Joe"} , -2458 , "Doe" , 555 , 100] */
|
14.将参数对象转换为数组
1
|
var
argArray = Array.prototype.slice.call(arguments);
|
15.验证一个给定参数是否为数字
1
2
3
|
function
isNumber(n){
return
!isNaN(parseFloat(n)) && isFinite(n);
}
|
16.验证一个给定的参数为数组
1
2
3
|
function
isArray(obj){
return
Object.prototype.toString.call(obj) ===
'[object Array]'
;
}
|
注意,如果toString()方法被重写了,你将不会得到预期结果。
或者你可以这样写
1
|
Array.isArray(obj);
// its a new Array method
|
同样,如果你使用多个frames,你可以使用instancesof,如果内容太多,结果同样会出错。
1
2
3
4
5
6
7
8
9
|
var
myFrame = document.createElement(
'iframe'
);
document.body.appendChild(myFrame);
var
myArray = window.frames[window.frames.length-1].Array;
var
arr =
new
myArray(a,b,10);
// [a,b,10]
// instanceof will not work correctly, myArray loses <span id="1_nwp" style="width: auto; height: auto; float: none;"><a id="1_nwl" style="text-decoration: none;" href="http://cpro.baidu.com/cpro/ui/uijs.php?c=news&cf=1001&ch=0&di=128&fv=17&jk=b214e2f7e7d8a432&k=his&k0=his&kdi0=0&luki=2&n=10&p=baidu&q=06011078_cpr&rb=0&rs=1&seller_id=1&sid=32a4d8e7f7e214b2&ssp2=1&stid=0&t=tpclicked3_hc&tu=u1922429&u=http%3A%2F%2Fwww%2Eadmin10000%2Ecom%2Fdocument%2F3589%2Ehtml&urlid=0" target="_blank" mpid="1"><span style="width: auto; height: auto; color: rgb(0, 0, 255); font-size: 14px; float: none;">his</span></a></span> constructor
// constructor is not shared between frames
arr
instanceof
Array;
// fals
|
17.从数字数组中获得最大值和最小值
1
2
3
|
var
numbers = [5, 458 , 120 , -215 , 228 , 400 , 122205, -85411];
var
maxInNumbers = Math.max.apply(Math, numbers);
var
minInNumbers = Math.min.apply(Math, numbers);
|
18.清空数组
1
2
|
var
myArray = [12 , 222 , 1000 ];
myArray.length = 0;
// myArray will be equal to [].
|
19.不要用delete从数组中删除项目
开发者可以使用split来代替使用delete来删除数组项。与其删除数组中未定义项目,还不如使用delete来替代。
1
2
3
4
5
|
var
items = [12, 548 ,
'a'
, 2 , 5478 ,
'foo'
, 8852, ,
'Doe'
,2154 , 119 ];
items.length;
// return 11
delete
items[3];
// return true
items.length;
// return 11
/* items will be equal to [12, 548, "a", undefined × 1, 5478, "foo", 8852, undefined × 1, "Doe", 2154, 119] */
|
也可以……
1
2
3
4
5
|
var
items = [12, 548 ,
'a'
, 2 , 5478 ,
'foo'
, 8852, ,
'Doe'
,2154 , 119 ];
items.length;
// return 11
items.splice(3,1) ;
items.length;
// return 10
/* items will be equal to [12, 548, "a", 5478, "foo", 8852, undefined × 1, "Doe", 2154, 119] */
|
delete方法应该删除一个对象属性
20.使用length属性缩短数组
如上文提到的清空数组,开发者还可以使用length属性缩短数组。
1
2
|
var
myArray = [12 , 222 , 1000 , 124 , 98 , 10 ];
myArray.length = 4;
// myArray will be equal to [12 , 222 , 1000 , 124].
|
如果你所定义的数组长度值过高,那么数组的长度将会改变,并且会填充一些未定义的值到数组里,数组的length属性不是只读的。
1
2
|
myArray.length = 10;
// the new array length is 10
myArray[myArray.length - 1] ;
// undefined
|