Use!! Operator to convert Boolean values
Sometimes we need to check whether a variable exists or whether the value has a valid value, and return the true value if it exists. In order to do such verification, we can use!! operator to achieve is very convenient and simple. Variable can be used for variable detection, as long as the value of the variable is: 0, null, "", "undefined or NaN will return false, otherwise return true. For example, the following 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
In this example, as long as account. case has a value greater than 0, account.hasMoney returns a value of true.
Use + to convert strings to numbers
This technique is very useful, it is very simple, can intersect string data into numbers, but it is only suitable for string data, otherwise it will return NaN, such as the following example:
function toNumber(strNumber) { return +strNumber; } console.log(toNumber("1234")); // 1234 console.log(toNumber("ACB")); // NaN
This also applies to Date, which in this case returns a timestamp number:
console.log(+new Date()) // 1461288164385
Union conditional
If you have a piece of code like this:
if (conected) { login(); }
You can also abbreviate variables and connect them with functions using & & as in the example above, which can be abbreviated as follows:
conected && login();
If some attributes or functions exist in an object, you can also do this detection, as shown in the following code:
user && user.login();
There is a default parameter feature in ES6. To simulate this feature in older browsers, you can use the | operator and pass in the default value as the second parameter. If the value returned by the first parameter is false, the second value will be considered a default value. The following is an 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
Cache array.length in a loop.
The trick is simple, and this can have a huge impact on performance when dealing with a large array loop. Basically, you will write an array of such synchronous iterations:
for(var i = 0; i < array.length; i++) { console.log(array[i]); }
If it's a small array, that's good. If you're dealing with a large array, this code will recalculate the size of the array every iteration, which will cause some delays. To avoid this phenomenon, array.length can be used as a cache:
var length = array.length; for(var i = 0; i < length; i++) { console.log(array[i]); }
You can also write in this way:
for(var i = 0, length = array.length; i < length; i++) { console.log(array[i]); }
Detecting attributes in objects
This trick is useful when you need to detect the existence of some attributes to avoid running undefined functions or attributes. If you plan to order some cross-compatible browser code, you may also use this trick. For example, if you want to use document.querySelector() to select an id and make it compatible with IE6 browsers, but this function does not exist in IE6 browsers, it is very useful to use this operator to detect the existence of this function, as follows:
if ('querySelector' in document) { document.querySelector("#id"); } else { document.getElementById("id"); }
In this example, if the document does not have a querySelector function, docuemnt.getElementById("id") is called.
Get the last element in the array
Array.prototype.slice(begin,end) is used to get the array elements between begin and end. If you do not set the end parameter, the default length of the array will be treated as the end value. But some students may not know that this function can also accept negative values as parameters. If you set a negative value as the value of begin, you can get the last element of the array. Such as:
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]
Array truncation
This little trick is mainly used to lock the size of arrays, which is very useful if it is used to delete some elements in arrays. For example, your array has 10 elements, but if you want only the first five elements, you can truncate the array by array.length=5. The following is an 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]
Replace all
The String.replace() function allows you to replace strings with strings or regular expressions. The function itself only replaces strings that appear for the first time. However, you can use the middle / g of regular expressions 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"
Merge arrays
If you want to merge two arrays, you usually 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];
Then this function is not suitable for merging two large arrays because it consumes a lot of memory to store newly created arrays. In this case, you can use Array.push().apply(arr1,arr2) instead of creating a new array. This method is not used to create a new array, it just combines the first and second numbers together, while reducing 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];
Converting NodeList to an array
If you run the document.querySelectorAll("p") function, it may return an array of DOM elements, the NodeList object. But this object does not have the function of array, such as sort(), reduce(), map(), filter(), etc. In order for these native array functions to be used on them, it is necessary to convert the list of nodes into an array. You can use []. slice.call(elements):
var elements = document.querySelectorAll("p"); // NodeList var arrayElements = [].slice.call(elements); // Now the NodeList is an array var arrayElements = Array.from(elements); // This is another way of converting NodeList to Array
Shuffling of array elements
For shuffling of array elements, no external libraries, such as Lodash, are needed, as long as this is done:
var list = [1,2,3]; console.log(list.sort(function() { Math.random() - 0.5 })); // [2,1,3]
Reference resources
Reprint address: http://www.codeceo.com/article/12-useful-javascript-tips.html