在前段时间,CSDN研发频道发表了超实用的JavaScript技巧及最佳实践(上),很多开发者都觉得里面所提到的技巧非常实用,基于此,我们再向大家推荐超实用的JavaScript技巧及最佳实践(下),希望对大家有所帮助。
文中所提供的代码片段都已经过最新版的Chrome 30测试,该浏览器使用V8 JavaScript引擎(V8 3.20.17.15)。
1.使用逻辑符号&&或者||进行条件判断
- var foo = 10;
- foo == 10 && doSomething(); // is the same thing as if (foo == 10) doSomething();
- foo == 5 || doSomething(); // is the same thing as if (foo != 5) doSomething();
var foo = 10; foo == 10 && doSomething(); // is the same thing as if (foo == 10) doSomething(); foo == 5 || doSomething(); // is the same thing as if (foo != 5) doSomething();
||也可以用来设置函数参数的默认值
- Function doSomething(arg1){
- Arg1 = arg1 || 10; // arg1 will have 10 as a default value if it’s not already set
- }
Function doSomething(arg1){ Arg1 = arg1 || 10; // arg1 will have 10 as a default value if it’s not already set }
2.使用map()方法来遍历数组
- var squares = [1,2,3,4].map(function (val) {
- return val * val;
- });
- // squares will be equal to [1, 4, 9, 16]
var squares = [1,2,3,4].map(function (val) { return val * val; }); // squares will be equal to [1, 4, 9, 16]
3.舍入小数位数
- var num =2.443242342;
- num = num.toFixed(4); // num will be equal to 2.4432
var num =2.443242342; num = num.toFixed(4); // num will be equal to 2.4432
4.浮点数问题
- 0.1 + 0.2 === 0.3 // is false
- 9007199254740992 + 1 // is equal to 9007199254740992
- 9007199254740992 + 2 // is equal to 9007199254740994
0.1 + 0.2 === 0.3 // is false 9007199254740992 + 1 // is equal to 9007199254740992 9007199254740992 + 2 // is equal to 9007199254740994
0.1+0.2等于0.30000000000000004,为什么会发生这种情况?根据IEEE754标准,你需要知道的是所有JavaScript数字在64位二进制内的都表示浮点数。开发者可以使用toFixed()和toPrecision()方法来解决这个问题。
5.使用for-in loop检查遍历对象属性
下面这段代码主要是为了避免遍历对象属性。
- for (var name in object) {
- if (object.hasOwnProperty(name)) {
- // do something with name
- }
- }
for (var name in object) { if (object.hasOwnProperty(name)) { // do something with name } }
6.逗号操作符
- var a = 0;
- var b = ( a++, 99 );
- console.log(a); // a will be equal to 1
- console.log(b); // b is equal to 99
var a = 0; var b = ( a++, 99 ); console.log(a); // a will be equal to 1 console.log(b); // b is equal to 99
7.计算或查询缓存变量
在使用jQuery选择器的情况下,开发者可以缓存DOM元素
- var navright = document.querySelector(‘#right‘);
- var navleft = document.querySelector(‘#left‘);
- var navup = document.querySelector(‘#up‘);
- var navdown = document.querySelector(‘#down‘);
var navright = document.querySelector(‘#right‘); var navleft = document.querySelector(‘#left‘); var navup = document.querySelector(‘#up‘); var navdown = document.querySelector(‘#down‘);
8.在将参数传递到isFinite()之前进行验证
- isFinite(0/0) ; // false
- isFinite("foo"); // false
- isFinite("10"); // true
- isFinite(10); // true
- isFinite(undifined); // false
- isFinite(); // false
- isFinite(null); // true !!!
isFinite(0/0) ; // false isFinite("foo"); // false isFinite("10"); // true isFinite(10); // true isFinite(undifined); // false isFinite(); // false isFinite(null); // true !!!
9.在数组中避免负向索引
- var numbersArray = [1,2,3,4,5];
- var from = numbersArray.indexOf("foo") ; // from is equal to -1
- numbersArray.splice(from,2); // will return [5]
var numbersArray = [1,2,3,4,5]; var from = numbersArray.indexOf("foo") ; // from is equal to -1 numbersArray.splice(from,2); // will return [5]
确保参数传递到indexOf()方法里是非负向的。
10.(使用JSON)序列化和反序列化
- var person = {name :‘Saad‘, age : 26, department : {ID : 15, name : "R&D"} };
- var stringFromPerson = JSON.stringify(person);
- /* stringFromPerson is equal to "{"name":"Saad","age":26,"department":{"ID":15,"name":"R&D"}}" */
- var personFromString = JSON.parse(stringFromPerson);
- /* personFromString is equal to person object */
var person = {name :‘Saad‘, age : 26, department : {ID : 15, name : "R&D"} }; var stringFromPerson = JSON.stringify(person); /* stringFromPerson is equal to "{"name":"Saad","age":26,"department":{"ID":15,"name":"R&D"}}" */ var personFromString = JSON.parse(stringFromPerson); /* personFromString is equal to person object */
11.避免使用eval()或Function构造函数
eval()和Function构造函数被称为脚本引擎,每次执行它们的时候都必须把源码转换成可执行的代码,这是非常昂贵的操作。
- var func1 = new Function(functionCode);
- var func2 = eval(functionCode);
var func1 = new Function(functionCode); var func2 = eval(functionCode);
12.避免使用with()方法
如果在全局区域里使用with()插入变量,那么,万一有一个变量名字和它名字一样,就很容易混淆和重写。
13.避免在数组里使用for-in loop
而不是这样用:
- var sum = 0;
- for (var i in arrayNumbers) {
- sum += arrayNumbers[i];
- }
var sum = 0; for (var i in arrayNumbers) { sum += arrayNumbers[i]; }
这样会更好:
- var sum = 0;
- for (var i = 0, len = arrayNumbers.length; i < len; i++) {
- sum += arrayNumbers[i];
- }
var sum = 0; for (var i = 0, len = arrayNumbers.length; i < len; i++) { sum += arrayNumbers[i]; }
因为i和len是循环中的第一个语句,所以每次实例化都会执行一次,这样执行起来就会比下面这个更快:
- for (var i = 0; i < arrayNumbers.length; i++)
for (var i = 0; i < arrayNumbers.length; i++)
为什么?数组长度arraynNumbers在每次loop迭代时都会被重新计算。
14.不要向setTimeout()和setInterval()方法里传递字符串
如果在这两个方法里传递字符串,那么字符串会像eval那样重新计算,这样速度就会变慢,而不是这样使用:
- setInterval(‘doSomethingPeriodically()‘, 1000);
- setTimeOut(‘doSomethingAfterFiveSeconds()‘, 5000);
setInterval(‘doSomethingPeriodically()‘, 1000); setTimeOut(‘doSomethingAfterFiveSeconds()‘, 5000);
相反,应该这样用:
- setInterval(doSomethingPeriodically, 1000);
- setTimeOut(doSomethingAfterFiveSeconds, 5000);
setInterval(doSomethingPeriodically, 1000); setTimeOut(doSomethingAfterFiveSeconds, 5000);
15.使用switch/case语句代替较长的if/else语句
如果有超过2个以上的case,那么使用switch/case速度会快很多,而且代码看起来更加优雅。
16.遇到数值范围时,可以选用switch/casne
- function getCategory(age) {
- var category = "";
- switch (true) {
- case isNaN(age):
- category = "not an age";
- break;
- case (age >= 50):
- category = "Old";
- break;
- case (age <= 20):
- category = "Baby";
- break;
- default:
- category = "Young";
- break;
- };
- return category;
- }
- getCategory(5); // will return "Baby"
function getCategory(age) { var category = ""; switch (true) { case isNaN(age): category = "not an age"; break; case (age >= 50): category = "Old"; break; case (age <= 20): category = "Baby"; break; default: category = "Young"; break; }; return category; } getCategory(5); // will return "Baby"
17.创建一个对象,该对象的属性是一个给定的对象
可以编写一个这样的函数,创建一个对象,该对象属性是一个给定的对象,好比这样:
- function clone(object) {
- function OneShotConstructor(){};
- OneShotConstructor.prototype= object;
- return new OneShotConstructor();
- }
- clone(Array).prototype ; // []
function clone(object) { function OneShotConstructor(){}; OneShotConstructor.prototype= object; return new OneShotConstructor(); } clone(Array).prototype ; // []
18.一个HTML escaper函数
- function escapeHTML(text) {
- var replacements= {"<": "<", ">": ">","&": "&", "\"": """};
- return text.replace(/[<>&"]/g, function(character) {
- return replacements[character];
- });
- }
function escapeHTML(text) { var replacements= {"<": "<", ">": ">","&": "&", "\"": """}; return text.replace(/[<>&"]/g, function(character) { return replacements[character]; }); }
19.在一个loop里避免使用try-catch-finally
try-catch-finally在当前范围里运行时会创建一个新的变量,在执行catch时,捕获异常对象会赋值给变量。
不要这样使用:
- var object = [‘foo‘, ‘bar‘], i;
- for (i = 0, len = object.length; i <len; i++) {
- try {
- // do something that throws an exception
- }
- catch (e) {
- // handle exception
- }
- }
var object = [‘foo‘, ‘bar‘], i; for (i = 0, len = object.length; i <len; i++) { try { // do something that throws an exception } catch (e) { // handle exception } }
应该这样使用:
- var object = [‘foo‘, ‘bar‘], i;
- try {
- for (i = 0, len = object.length; i <len; i++) {
- // do something that throws an exception
- }
- }
- catch (e) {
- // handle exception
- }
var object = [‘foo‘, ‘bar‘], i; try { for (i = 0, len = object.length; i <len; i++) { // do something that throws an exception } } catch (e) { // handle exception }
20.给XMLHttpRequests设置timeouts
如果一个XHR需要花费太长时间,你可以终止链接(例如网络问题),通过给XHR使用setTimeout()解决。
- var xhr = new XMLHttpRequest ();
- xhr.onreadystatechange = function () {
- if (this.readyState == 4) {
- clearTimeout(timeout);
- // do something with response data
- }
- }
- var timeout = setTimeout( function () {
- xhr.abort(); // call error callback
- }, 60*1000 /* timeout after a minute */ );
- xhr.open(‘GET‘, url, true);
- xhr.send();
var xhr = new XMLHttpRequest (); xhr.onreadystatechange = function () { if (this.readyState == 4) { clearTimeout(timeout); // do something with response data } } var timeout = setTimeout( function () { xhr.abort(); // call error callback }, 60*1000 /* timeout after a minute */ ); xhr.open(‘GET‘, url, true); xhr.send();
此外,通常你应该完全避免同步Ajax调用。
21.处理WebSocket超时
一般来说,当创建一个WebSocket链接时,服务器可能在闲置30秒后链接超时,在闲置一段时间后,防火墙也可能会链接超时。
为了解决这种超时问题,你可以定期地向服务器发送空信息,在代码里添加两个函数:一个函数用来保持链接一直是活的,另一个用来取消链接是活的,使用这种方法,你将控制超时问题。
添加一个timeID……
- var timerID = 0;
- function keepAlive() {
- var timeout = 15000;
- if (webSocket.readyState == webSocket.OPEN) {
- webSocket.send(‘‘);
- }
- timerId = setTimeout(keepAlive, timeout);
- }
- function cancelKeepAlive() {
- if (timerId) {
- cancelTimeout(timerId);
- }
- }
var timerID = 0; function keepAlive() { var timeout = 15000; if (webSocket.readyState == webSocket.OPEN) { webSocket.send(‘‘); } timerId = setTimeout(keepAlive, timeout); } function cancelKeepAlive() { if (timerId) { cancelTimeout(timerId); } }
keepAlive()方法应该添加在WebSocket链接方法onOpen()的末端,cancelKeepAlive()方法放在onClose()方法下面。
22.记住,最原始的操作要比函数调用快
对于简单的任务,最好使用基本操作方式来实现,而不是使用函数调用实现。
例如
- var min = Math.min(a,b);
- A.push(v);
var min = Math.min(a,b); A.push(v);
基本操作方式:
- var min = a < b ? a b;
- A[A.length] = v;
var min = a < b ? a b; A[A.length] = v;
23.编码时注意代码的美观、可读
JavaScript是一门非常好的语言,尤其对于前端工程师来说,JavaScript也非常重要,点击 这里可以访问更多优秀的JavaScript资源。