Home > Web Front-end > JS Tutorial > Summary of tips for reducing and optimizing code in JavaScript

Summary of tips for reducing and optimizing code in JavaScript

伊谢尔伦
Release: 2017-07-20 10:07:33
Original
1459 people have browsed it

1) Convert variables to boolean type using !!

Sometimes, we need to check if some variables exist, or if it has a valid value, thus treating their values ​​as true. For doing such a check, you can use || (double negation operator), which automatically converts any type of data into a boolean value. Only these variables will return false: 0, null, "", undefined or NaN, Everything else returns true. Let's take a look at this simple example:


function Account(cash) { 
 this.cash = cash; 
 this.hasMoney = !!cash; 
} 
var account = new Account(100.50); 
console.log(account.cash); // 100.50 
console.log(account.hasMoney); // true 
var emptyAccount = new Account(0); 
console.log(emptyAccount.cash); // 0 
console.log(emptyAccount.hasMoney); // false
Copy after login

In this example, if the value of account.cash is greater than zero, the value of account.hasMoney is true.

2) Use + to convert the variable into a number

This conversion is super simple, but it only works with numeric strings, otherwise it will return NaN (not a number) . Take a look at this example:


function toNumber(strNumber) { 
 return +strNumber; 
} 
console.log(toNumber("1234")); // 1234 
console.log(toNumber("ACB")); // NaN
Copy after login

This conversion operation can also be applied to Date, in which case it will return a timestamp:


console.log(+new Date()) // 1461288164385
Copy after login

3) Short circuit condition

If you have seen this similar code:


if (conected) { 
 login(); 
}
Copy after login

Then you can use && (AND operator) between these two variables to shorten the code. For example, the previous code can be reduced to one line:


conected && login();
Copy after login

You can also use this method to check whether certain properties or functions exist in an object. Similar to the following code:


user && user.login();
Copy after login

4) Use || to set the default value

There are default parameters in ES6 this function. To emulate this functionality in older browsers, you can use || (OR operator) and pass the default value as its second argument. If the first parameter returns false, the second parameter will be returned as the default value. Take a look at this example:


function User(name, age) { 
 this.name = name || "Oliver Queen"; 
 this.age = age || 27; 
} 
var user1 = new User(); 
console.log(user1.name); // Oliver Queen 
console.log(user1.age); // 27 
var user2 = new User("Barry Allen", 25); 
console.log(user2.name); // Barry Allen 
console.log(user2.age); // 25
Copy after login

5) Caching array.length in a loop

This trick is very simple and works in a loop This avoids a huge impact on performance when working with large arrays. Basically this is how almost everyone uses for to loop over an array:


for (var i = 0; i < array.length; i++) { 
 console.log(array[i]); 
}
Copy after login

If you're working with smaller arrays, that's fine, but if you're dealing with large arrays , this code will repeatedly calculate the size of the array in each loop, which will cause a certain delay. To avoid this, you can cache array.length in a variable so that the cache is used instead of array.length each time in the loop:


var length = array.length; 
for (var i = 0; i < length; i++) { 
 console.log(array[i]); 
}
Copy after login

For more brevity , you can write like this:


for (var i = 0, length = array.length; i < length; i++) { 
 console.log(array[i]); 
}
Copy after login

6) Detect attributes in the object

When you need to check whether certain attributes exist, This technique is useful when avoiding running undefined functions or properties. You might also use this technique if you plan to write cross-browser code. For example, let's assume that you need to write code that is compatible with older versions of Internet Explorer 6, and you want to use document.querySelector() to get certain elements by ID. However, in modern browsers, this function does not exist. So, to check if this function exists, you can use the in operator. Take a look at this example:


if (&#39;querySelector&#39; in document) { 
 document.querySelector("#id"); 
} else { 
 document.getElementById("id"); 
}
Copy after login

In this case, if there is no querySelector function in the document, it will use document.getElementById() instead.

7) Get the last element of the array

Array.prototype.slice(begin, end) can be used to cut the array. But if the value of the end parameter end is not set, the function will automatically set end to the array length value. I think few people know that this function can accept negative values. If you set begin to a negative number, you can get the reciprocal element from the array:


var array = [1, 2, 3, 4, 5, 6]; 
console.log(array.slice(-1)); // [6] 
console.log(array.slice(-2)); // [5,6] 
console.log(array.slice(-3)); // [4,5,6]
Copy after login

8) Array truncation

This technique can lock the size of the array, which is very useful for deleting a fixed number of elements in the array. For example, if you have an array with 10 elements, but you only want to get the first five elements, you can stage the array by setting array.length = 5. Take a look at this example:


var array = [1, 2, 3, 4, 5, 6]; 
console.log(array.length); // 6 
array.length = 3; 
console.log(array.length); // 3 
console.log(array); // [1,2,3]
Copy after login

9) Replace all

String.replace() function allows using String and Regex to replace String, this function itself can only replace the first matching string. But you can add /g at the end of the regular expression to simulate the replaceAll() function:


var string = "john john"; 
console.log(string.replace(/hn/, "ana")); // "joana john" 
console.log(string.replace(/hn/g, "ana")); // "joana joana"
Copy after login

10) Merging arrays

If you need to merge two arrays, you can use the Array.concat() function:


var array1 = [1, 2, 3]; 
var array2 = [4, 5, 6]; 
console.log(array1.concat(array2)); // [1,2,3,4,5,6];
Copy after login

However, this function is not suitable for large arrays because it will A new array will be created and consume a lot of memory. In this case you can use Array.push.apply(arr1, arr2) which does not create a new array but merges the second array into the first array to reduce memory usage:


var array1 = [1, 2, 3]; 
var array2 = [4, 5, 6]; 
console.log(array1.push.apply(array1, array2)); // [1,2,3,4,5,6];
Copy after login

11) Convert NodeList into an array

如果运行document.querySelectorAll("p")函数,它会返回一个DOM元素数组,即NodeList对象。但是这个对象并没有一些属于数组的函数,例如:sort(),reduce(),map(),filter()。为了启用这些函数,以及数组的其他的原生函数,你需要将NodeList转换为数组。要进行转换,只需使用这个函数:[] .slice.call(elements):


var elements = document.querySelectorAll("p"); // NodeList  
var arrayElements = [].slice.call(elements); // 现在已经转换成数组了 
var arrayElements = Array.from(elements); // 把NodeList转换成数组的另外一个方法
Copy after login

12) 对数组元素进行洗牌

如果要像外部库Lodash那样对数据元素重新洗牌,只需使用这个技巧:


var list = [1, 2, 3];  
console.log(list.sort(function() {  
  return Math.random() - 0.5 
})); // [2,1,3]
Copy after login

The above is the detailed content of Summary of tips for reducing and optimizing code in JavaScript. 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