Special usage of javascriptd

1. Use!! Convert variables to Boolean types.

Sometimes, we need to check whether some variables exist, or whether they have valid values, so that their values are considered true. For such a check, you can use | (double negative operator), which automatically converts any type of data to Boolean values. Only these variables return false: 0, null, ","undefined"or NaN, and all others return 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  

2. Use + to convert variables into numbers.

This conversion is super simple, but it only applies to numeric strings, otherwise NaN (not numbers) will be returned. Look at this example:

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

This transformation operation also works on Date, in which case it returns a timestamp:

console.log(+new Date()) // 1461288164385  

3. Short circuit condition.

If you've ever seen code like this:

if (conected) {  
    login();
}

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

conected && login();  

You can also use this method to check whether there are certain attributes or functions in the object. Similar to the following code:

user && user.login(); 

4. Use | | to set default values.

There is a default parameter function in ES6. To simulate this function in older browsers, you can use | (OR operator) and take the default value as its second parameter. If the first parameter returns false, the second parameter will be returned as the default value. 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  

5. Cache array.length in the loop.

This technique is very simple and can avoid a huge performance impact when large arrays are processed in a loop. Almost everyone uses for to iterate over an array in this way:

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

If you use smaller arrays, that's fine, but if you deal with large arrays, the code will calculate the size of arrays repeatedly in each loop, which will cause a certain delay. To avoid this, you can cache array.length in variables to replace array.length with caching every time in a loop:

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

To be more concise, you can write as follows:

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

6. Detecting attributes in objects.

This technique is useful when you need to check for the existence of certain attributes to avoid running undefined functions or attributes. If you plan to write cross-browser code, you may also use this technology. For example, let's assume that you need to write code that is compatible with older Internet Explorer 6 and that you want to use document.querySelector() to retrieve certain elements by ID. However, in modern browsers, this function does not exist. So, to check whether this function exists, you can use the in operator. Look at this example:

if ('querySelector' in document) {  
    document.querySelector("#id");
} else {
    document.getElementById("id");
}

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 tailor arrays. But if the value of the end parameter is not set, the function automatically sets the end to an 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 elements 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]  

8. Array truncation.

This technique can lock the size of an array, which is very useful for deleting a fixed number of elements in an array. For example, if you have an array of 10 elements, but you only want to get the first five elements, you can stage the array by setting array.length = 5. 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]  

9. Replace all.

The String.replace() function allows String and Regex to replace strings, and the 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"  

10. Merge 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];  

However, this function is not suitable for large arrays because it will create a new array 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 combines 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];  

11. Convert NodeList to an array.

If you run the document.querySelectorAll("p") function, it returns an array of DOM elements, the NodeList object. But this object does not have some functions that belong to arrays, such as sort(), reduce(), map(), filter(). To enable these functions, as well as other native functions of arrays, you need to convert NodeList into arrays. To convert, you only need to use this function: []. slice.call (elements):

var elements = document.querySelectorAll("p"); // NodeList  
var arrayElements = [].slice.call(elements); // Now it's converted to an array.
var arrayElements = Array.from(elements); // Another way to convert NodeList into an array

12. Shuffle the array elements.

 

If you want to re-shuffle data elements like Lodash, you only need to use this technique:

 

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

 

Attachment: Reproduced from CSDN, invade and delete.

 

 

Keywords: Javascript

Added by chanfuterboy on Tue, 02 Jul 2019 01:29:10 +0300