Home > Web Front-end > JS Tutorial > 45 classic tips for JavaScript development

45 classic tips for JavaScript development

黄舟
Release: 2017-03-14 15:17:01
Original
1434 people have browsed it

JavaScript is a world-leading programming language that can be used for web development, mobile application development (PhoneGap, Appcelerator), and server-side development (Node.jsand Wakanda) and so on. JavaScript is also the first language for many novices to enter the world of programming. It can be used to display a simple prompt box in the browser, or to control the robot through nodebot or nodruino. Developers who can write JavaScript code with clear structure and high performance are now the most sought after people in the recruitment market.

In this article, I will share some JavaScript tips, secrets, and best practices that, with a few exceptions, apply to both the browser's JavaScript engine and the server-side JavaScript interpreter.

The sample code in this article passed the test on the latest version of Google Chrome 30 (V8 3.20.17.15).

1. When assigning a value to a variable for the first time, be sure to use the var keyword

If the variable is not declared and assigned directly, it will be used as a new value by default. Global variables, try to avoid using global variables.

2. Use === instead of ==

== and != Operators will automatically convert data types if necessary. But === and !== will not, they will compare the value and data type at the same time, which also makes them better than == and !=Fast. The logical results of

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

3, underfined, <a href="http://www.php.cn/wiki/62.html" target="_blank">null</a>, 0, false, NaN, empty string are all For false

4, use a semicolon at the end of the line

In practice, it is best to use a semicolon. It doesn’t matter if you forget to write it. In most cases, the JavaScript interpreter will automatically add it. For more information on why semicolons are used, please refer to the article The Truth About Semicolons in JavaScript.

5. Use ObjectConstructor

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

6. Use typeof, instanceof and contructor# carefully

  • ##typeof: JavaScript unary operator, used to return the original type of the variable in the form of a string. Note, typeof null object<a href="http://www.php.cn/wiki/60.html" target="_blank"></a> will also be returned. Most object types (arrayArray, timeDate, etc.) will also return object

  • contructor: Internal prototype properties , which can be overridden by code

  • instanceof: JavaScript operator, it will search for in the constructor in the prototype chain, and return true if found, otherwise false## will be returned.

    #
    var arr = ["a", "b", "c"];
    typeof arr;   // 返回 "object" 
    arr instanceof Array // true
    arr.constructor();  //[]
    Copy after login
  • 7. Use self-calling
function

The function is automatically executed directly after creation, usually called self-calling

Anonymous function

(Self-Invoked Anonymous Function) or directly call Function Expression(Immediately Invoked Function Expression). The format is as follows:

8. Get random members from the array

var items = [12, 548 , &#39;a&#39; , 2 , 5478 , &#39;foo&#39; , 8852, , &#39;Doe&#39; , 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 used when generating fake data for testing There are special numbers, such as salaries within a specified range.

var x = Math.floor(Math.random() * (max - min + 1)) + min;
Copy after login

10. Generate a numeric 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 a random alphanumeric string

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. Disorganize the order of the numeric 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 special code to implement it (such as Fisher-Yates algorithm), you can see StackOverFlow## This discussion on #. 13. String spaces removal

Java,

C

# and PHP and other languages ​​have implemented special string space removal functions, but they are not available in JavaScript. You can Use the following code to function a

trim function for the String object: <a href="http://www.php.cn/wiki/1438.html" target="_blank"><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:js;toolbar:false;">String.prototype.trim = function(){return this.replace(/^\s+|\s+$/g, &quot;&quot;);};</pre><div class="contentsignin">Copy after login</div></div></a>The new JavaScript engine already has trim( )

's native implementation.

14、数组之间追加

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、对象转换为数组

var argArray = Array.prototype.slice.call(arguments);
Copy after login

16、验证是否是数字

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

17、验证是否是数组

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

但如果toString()方法被重写过得话,就行不通了。也可以使用下面的方法:

Array.isArray(obj); // its a new Array method
Copy after login

如果在浏览器中没有使用frame,还可以用instanceof,但如果上下文太复杂,也有可能出错。

var myFrame = document.createElement(&#39;iframe&#39;);
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

19、清空数组

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

20、不要直接从数组中<a href="http://www.php.cn/wiki/1298.html" target="_blank">delete</a>remove元素

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

切忌:

var items = [12, 548 ,&#39;a&#39; , 2 , 5478 , &#39;foo&#39; , 8852, , &#39;Doe&#39; ,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 ,&#39;a&#39; , 2 , 5478 , &#39;foo&#39; , 8852, , &#39;Doe&#39; ,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、使得<a href="http://www.php.cn/code/9794.html" target="_blank">map</a>()函数方法对数据循环

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

为什么呢?因为0.1+0.2等于0.30000000000000004。JavaScript的数字都遵循IEEE 754标准构建,在内部都是64位浮点小数表示,具体可以参见JavaScript中的数字是如何编码的.

可以通过使用toFixed()<a href="http://www.php.cn/wiki/904.html" target="_blank">toP</a>recision()来解决这个问题。

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(&#39;#right&#39;); 
var navleft = document.querySelector(&#39;#left&#39;); 
var navup = document.querySelector(&#39;#up&#39;); 
var navdown = document.querySelector(&#39;#down&#39;);
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 :&#39;Saad&#39;, 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
Copy after login

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

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

var func1 = new Function(functionCode);
var func2 = eval(functionCode);
Copy after login
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

另外一个好处是,ilen两个变量是在for循环的第一个声明中,二者只会初始化一次,这要比下面这种写法快:

for (var i = 0; i < arrayNumbers.length; i++)
Copy after login

35、传给setInterval()set<a href="http://www.php.cn/wiki/1268.html" target="_blank">Time</a>out()使用函数而不是字符串

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

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

而是用:

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

36、使用<a href="http://www.php.cn/wiki/132.html" target="_blank">switch</a>/case代替一大叠的if/<a href="http://www.php.cn/wiki/111.html" target="_blank">else</a>

当判断有超过两个分支的时候使用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 = [&#39;foo&#39;, &#39;bar&#39;], 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 = [&#39;foo&#39;, &#39;bar&#39;], 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(&#39;GET&#39;, 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(&#39;&#39;);  
    }  
    timerId = setTimeout(keepAlive, timeout);  
}  
function cancelKeepAlive() {  
    if (timerId) {  
        cancelTimeout(timerId);  
    }  
}
Copy after login

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

43、时间注意原始操作符比函数调用快,使用VanillaJS

比如,一般不要这样:

var min = Math.min(a,b); 
A.push(v);
Copy after login

可以这样来代替:

var min = a < b ? a : b; 
A[A.length] = v;
Copy after login

44、开发时注意代码结构,上线前检查并压缩JavaScript代码

别忘了在写代码时使用一个代码美化工具。使用JSLint(一个语法检查工具)并且在上线前压缩代码(比如使用JSMin)。注:现在代码压缩一般推荐 UglifyJS (http://www.php.cn/)

45、JavaScript博大精深,这里有些不错的学习资源

  • Code Academy资源:http://www.codecademy.com/tracks/javascript

  • Marjin Haverbekex编写的Eloquent JavaScript:http://eloquentjavascript.net/

  • John Resig编写的Advanced JavaScript:http://ejohn.org/apps/learn/






The above is the detailed content of 45 classic tips for JavaScript development. For more information, please follow other related articles on the PHP Chinese website!

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