Home > Web Front-end > JS Tutorial > body text

Share classic JavaScript development skills_javascript skills

WBOY
Release: 2016-05-16 15:30:39
Original
986 people have browsed it

Sharing classic JavaScript development skills with everyone:

1. Be sure to use the var keyword when assigning a value to a variable for the first time

If a variable is assigned directly without being declared, it will be used as a new global variable by default. Try to avoid using global variables.
2. Use === instead of ==

The

== and != operators automatically convert data types if necessary. But === and !== don't, they compare values ​​and data types at the same time, which also makes them faster than == and !=.
[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. The logical results of underfined, null, 0, false, NaN, and empty string are all false

4. Use a semicolon at the end of the line

In practice, it is best to use semicolons. It doesn’t matter if you forget to write them. In most cases, the JavaScript interpreter will add them automatically.

5. Use object constructor

function Person(firstName, lastName){
 this.firstName = firstName;
 this.lastName = lastName;
}
var Saad = new Person("Saad", "Mousliki");
Copy after login

6. Use typeof, instanceof and constructor carefully

  • typeof: JavaScript unary operator, used to return the original type of the variable in the form of a string. Note that typeof null will also return object, and most object types (array, date, etc.) will also return object
  • constructor: Internal prototype property, can be overridden through code
  • instanceof: JavaScript operator, which will search in the constructor in the prototype chain. If found, it will return true, otherwise it will return false
var arr = ["a", "b", "c"];
typeof arr; // 返回 "object" 
arr instanceof Array // true
arr.constructor(); //[]
Copy after login

7. Use self-calling functions

The function is automatically executed directly after creation, usually called a self-invoked anonymous function (Self-Invoked Anonymous Function) or directly called function expression (Immediately Invoked Function Expression). The format is as follows:

(function(){
 // 置于此处的代码将自动执行
})(); 
(function(a,b){
 var result = a+b;
 return result;
})(10,20)
Copy after login

8. Randomly obtain members from the array

var items = [12, 548 , 'a' , 2 , 5478 , 'foo' , 8852, , 'Doe' , 2145 , 119];
var randomItem = items[Math.floor(Math.random() * items.length)];
Copy after login

9. Get random numbers within the specified range

This function is particularly useful when generating fake data for testing, such as salaries within a specified range.

Copy code The code is as follows:
var x = Math.floor(Math.random() * (max - min 1 )) min;

10. Generate a digital array from 0 to the specified value

var numbersArray = [] , max = 100;
for( var i=1; numbersArray.push(i++) < max;); // numbers = [1,2,3 ... 100]
Copy after login

11. Generate random alphanumeric strings

function generateRandomAlphaNum(len) {
 var rdmString = "";
 for( ; rdmString.length < len; rdmString += Math.random().toString(36).substr(2));
 return rdmString.substr(0, len);
}
Copy after login

12. Disrupt the order of the number array

var numbers = [5, 458 , 120 , -215 , 228 , 400 , 122205, -85411];
numbers = numbers.sort(function(){ return Math.random() - 0.5});
/* numbers 数组将类似于 [120, 5, 228, -215, 400, 458, -85411, 122205] */
Copy after login

The built-in array sorting function of JavaScript is used here. A better way is to use specialized code to implement it (such as Fisher-Yates algorithm). You can see this discussion on StackOverFlow.
13. Remove spaces from strings

Java, C#, PHP and other languages ​​all implement special string space removal functions, but they are not available in JavaScript. You can use the following code to configure the String object function through the following code Atrim function:
String.prototype.trim = function(){return this.replace(/^s |s $/g, "");};
The new JavaScript engine already has a native implementation of trim().
14. Append between arrays

var array1 = [12 , "foo" , {name "Joe"} , -2458];
var array2 = ["Doe" , 555 , 100];
Array.prototype.push.apply(array1, array2);
/* array1 值为 [12 , "foo" , {name "Joe"} , -2458 , "Doe" , 555 , 100] */
Copy after login

15. Convert object to array

Copy code The code is as follows:
var argArray = Array.prototype.slice.call(arguments);

16. Verify whether it is a number

function isNumber(n){
 return !isNaN(parseFloat(n)) && isFinite(n);
}
Copy after login

17. Verify whether it is an array

function isArray(obj){
 return Object.prototype.toString.call(obj) === '[object Array]' ;
}
Copy after login

But if the toString() method is overridden, it won’t work. You can also use the following method:

Copy code The code is as follows:
Array.isArray(obj); // its a new Array method

If frame is not used in the browser, instanceof can also be used, but if the context is too complex, errors may occur.

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] 
// myArray 的构造器已经丢失,instanceof 的结果将不正常
// 构造器是不能跨 frame 共享的
arr instanceof Array; // false
Copy after login

18、获取数组中的最大值和最小值

var numbers = [5, 458 , 120 , -215 , 228 , 400 , 122205, -85411]; 
var maxInNumbers = Math.max.apply(Math, numbers); 
var minInNumbers = Math.min.apply(Math, numbers);
Copy after login

详细内容可以参考这篇文章: 《JavaScript如何获取数组最大值和最小值》

19、清空数组

var myArray = [12 , 222 , 1000 ]; 
myArray.length = 0; // myArray will be equal to [].
Copy after login

20、不要直接从数组中delete或remove元素

如果对数组元素直接使用delete,其实并没有删除,只是将元素置为了undefined。数组元素删除应使用splice
切忌:

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 结果为 [12, 548, "a", undefined × 1, 5478, "foo", 8852, undefined × 1, "Doe", 2154, 119] */
Copy after login

而应:

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 结果为 [12, 548, "a", 5478, "foo", 8852, undefined × 1, "Doe", 2154, 119]
Copy after login

删除对象的属性时可以使用delete。
21、使用length属性截断数组

前面的例子中用length属性清空数组,同样还可用它来截断数组:

var myArray = [12 , 222 , 1000 , 124 , 98 , 10 ]; 
myArray.length = 4; // myArray will be equal to [12 , 222 , 1000 , 124].
Copy after login

与此同时,如果把length属性变大,数组的长度值变会增加,会使用undefined来作为新的元素填充。length是一个可写的属性。

myArray.length = 10; // the new array length is 10 
myArray[myArray.length - 1] ; // undefined
Copy after login

22、在条件中使用逻辑与或

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();
Copy after login

逻辑或还可用来设置默认值,比如函数参数的默认值。

function doSomething(arg1){ 
 arg1 = arg1 || 10; // arg1 will have 10 as a default value if it's not already set
}
Copy after login

23、使得map()函数方法对数据循环

var squares = [1,2,3,4].map(function (val) { 
 return val * val; 
}); 
// squares will be equal to [1, 4, 9, 16]
Copy after login

24、保留指定小数位数

var num =2.443242342;
num = num.toFixed(4); // num will be equal to 2.4432
Copy after login

注意,toFixec()返回的是字符串,不是数字。
25、浮点计算的问题

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。JavaScript的数字都遵循IEEE 754标准构建,在内部都是64位浮点小数表示,具体可以参见JavaScript中的数字是如何编码的.
可以通过使用toFixed()和toPrecision()来解决这个问题。
26、通过for-in循环检查对象的属性

下面这样的用法,可以防止迭代的时候进入到对象的原型属性中。

for (var name in object) { 
 if (object.hasOwnProperty(name)) { 
  // do something with name
 } 
}
Copy after login

27、逗号操作符

var a = 0; 
var b = ( a++, 99 ); 
console.log(a); // a will be equal to 1 
console.log(b); // b is equal to 99
Copy after login

28、临时存储用于计算和查询的变量

在jQuery选择器中,可以临时存储整个DOM元素。

var navright = document.querySelector('#right'); 
var navleft = document.querySelector('#left'); 
var navup = document.querySelector('#up'); 
var navdown = document.querySelector('#down');
Copy after login

29、提前检查传入isFinite()的参数

isFinite(0/0) ; // false
isFinite("foo"); // false
isFinite("10"); // true
isFinite(10); // true
isFinite(undefined); // false
isFinite(); // false
isFinite(null); // true,这点当特别注意
Copy after login

30、避免在数组中使用负数做索引

var numbersArray = [1,2,3,4,5];
 var from = numbersArray.indexOf("foo") ; // from is equal to -1
 numbersArray.splice(from,2); // will return [5]
Copy after login

注意传给splice的索引参数不要是负数,当是负数时,会从数组结尾处删除元素。
31、用JSON来序列化与反序列化

var person = {name :'Saad', age : 26, department : {ID : 15, name : "R&D"} };
var stringFromPerson = JSON.stringify(person);
/* stringFromPerson 结果为 "{"name":"Saad","age":26,"department":{"ID":15,"name":"R&D"}}" */
var personFromString = JSON.parse(stringFromPerson);
/* personFromString 的值与 person 对象相同 */
Copy after login

32、不要使用eval()或者函数构造器

eval()和函数构造器(Function consturctor)的开销较大,每次调用,JavaScript引擎都要将源代码转换为可执行的代码。

var func1 = new Function(functionCode);
var func2 = eval(functionCode);
Copy after login

33、避免使用with()

使用with()可以把变量加入到全局作用域中,因此,如果有其它的同名变量,一来容易混淆,二来值也会被覆盖。
34、不要对数组使用for-in

避免:

var sum = 0; 
for (var i in arrayNumbers) { 
 sum += arrayNumbers[i]; 
}
Copy after login

而是:

var sum = 0; 
for (var i = 0, len = arrayNumbers.length; i < len; i++) { 
 sum += arrayNumbers[i]; 
}
Copy after login

另外一个好处是,i和len两个变量是在for循环的第一个声明中,二者只会初始化一次,这要比下面这种写法快:
for (var i = 0; i < arrayNumbers.length; i++)
35、传给setInterval()和setTimeout()时使用函数而不是字符串

如果传给setTimeout()和setInterval()一个字符串,他们将会用类似于eval方式进行转换,这肯定会要慢些,因此不要使用:

setInterval('doSomethingPeriodically()', 1000); 
setTimeout('doSomethingAfterFiveSeconds()', 5000);
Copy after login

而是用:

setInterval(doSomethingPeriodically, 1000); 
setTimeout(doSomethingAfterFiveSeconds, 5000);
Copy after login

36、使用switch/case代替一大叠的if/else

当判断有超过两个分支的时候使用switch/case要更快一些,而且也更优雅,更利于代码的组织,当然,如果有超过10个分支,就不要使用switch/case了。
37、在switch/case中使用数字区间

其实,switch/case中的case条件,还可以这样写:

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); // 将返回 "Baby"
Copy after login

38、使用对象作为对象的原型

下面这样,便可以给定对象作为参数,来创建以此为原型的新对象:

function clone(object) { 
 function OneShotConstructor(){}; 
 OneShotConstructor.prototype = object; 
 return new OneShotConstructor(); 
} 
clone(Array).prototype ; // []
Copy after login

39、HTML字段转换函数

function escapeHTML(text) { 
 var replacements= {"<": "<", ">": ">","&": "&", "\"": """};      
 return text.replace(/[<>&"]/g, function(character) { 
  return replacements[character]; 
 }); 
}
Copy after login

40、不要在循环内部使用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 
 } 
}
Copy after login

而应该:

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 
}
Copy after login

41、使用XMLHttpRequests时注意设置超时

XMLHttpRequests在执行时,当长时间没有响应(如出现网络问题等)时,应该中止掉连接,可以通过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();
Copy after login

同时需要注意的是,不要同时发起多个XMLHttpRequests请求。
42、处理WebSocket的超时

通常情况下,WebSocket连接创建后,如果30秒内没有任何活动,服务器端会对连接进行超时处理,防火墙也可以对单位周期没有活动的连接进行超时处理。
为了防止这种情况的发生,可以每隔一定时间,往服务器发送一条空的消息。可以通过下面这两个函数来实现这个需求,一个用于使连接保持活动状态,另一个专门用于结束这个状态。

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); 
 } 
}
Copy after login

keepAlive()函数可以放在WebSocket连接的onOpen()方法的最后面,cancelKeepAlive()放在onClose()方法的最末尾。

以上就是为大家分享的javascript开发技巧,希望对大家的学习有所帮助。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template