In this article, we will share with you 12 tips about JavaScript. These tips may help you solve some problems in your actual work.
Use the !! operator to convert the boolean value
Sometimes we need to check whether a variable exists or check whether the value has a valid value, and if it exists, it returns true. In order to do such verification, we can use the !! operator to implement it is very convenient and simple. For variables, you can use !!variable for detection. As long as the value of the variable is: 0, null, " ", undefined or NaN, it will return false, otherwise it will 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.50console.log(account.hasMoney); // truevar emptyAccount = new Account(0);console.log(emptyAccount.cash); // 0console.log(emptyAccount.hasMoney); // falseIn this example, as long as the value of account.cash is greater than 0, the value returned by account.hasMoney is true.
Use + to convert strings to numbers
This trick is very useful. It is very simple and can be converted into numbers by intersecting string data. However, it is only suitable for string data, otherwise NaN will be returned, such as the following example:
function toNumber(strNumber) { return +strNumber;}console.log(toNumber("1234")); // 1234console.log(toNumber("ACB")); // NaNThis also works for Date, in this case it will return a timestamp number:
console.log(+new Date()) // 1461288164385
and conditional
If you have a code like this:
if (conected) { login();}You can also abbreviate variables and use && and concatenate them together. For example, the above example can be abbreviated as follows:
conected && login();
If some properties or functions exist in an object, you can also do the detection, as shown in the following code:
user && user.login();
Use || operator
There is a default parameter feature in ES6. To simulate this feature in older browsers, the || operator can be used and the default value will be passed in as a second parameter. If the value returned by the first parameter is false, the second value will be considered a default value. As in the following example:
function User(name, age) { this.name = name || "Oliver Queen"; this.age = age || 27;}var user1 = new User();console.log(user1.name); // Oliver Queenconsole.log(user1.age); // 27var user2 = new User("Barry Allen", 25);console.log(user2.name); // Barry Allenconsole.log(user2.age); // 25Cache array.length in loop
This trick is very simple, and this will have a very large impact on performance when dealing with a large array loop. Basically, everyone will write an array of synchronous iterations like this:
for(var i = 0; i < array.length; i++) { console.log(array[i]);}If it's a small array, this is great, if you're dealing with a large array, this code will recalculate the array size at each iteration, which will cause some delay. 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 it like this:
for(var i = 0, length = array.length; i < length; i++) { console.log(array[i]);}Detect properties in objects
This trick is useful when you need to detect whether some properties exist and avoid running undefined functions or properties. If you plan to customize some cross-compatible browser code, you may also use this tip. For example, 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, so it is very useful to use this operator to detect whether this function exists, such as the following example:
if ('querySelector' in document) { document.querySelector("#id");} else { document.getElementById("id");}In this example, if the querySelector function does not exist in the document, then the document is called.
Get the last element in the array
Array.prototype.slice(begin, end) is used to obtain the array elements between begin and end. If you do not set the end parameter, the default length value of the array will be regarded 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, then you can get the last element of the array. like:
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 trick is mainly used to lock the size of the array, and is very useful if used to delete some elements in the array. For example, your array has 10 elements, but you only want to only have the first five elements, then you can truncate the array by array.length=5. As in the following example:
var array = [1,2,3,4,5,6];console.log(array.length); // 6array.length = 3;console.log(array.length); // 3console.log(array); // [1,2,3]
Replace all
The String.replace() function allows you to use strings or regular expressions to replace strings. This function itself only replaces the first string. However, you can use /g in regular expressions to simulate the replaceAll() function 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 will 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];
This function is then not suitable for merging two large arrays, because it will consume a lot of memory to store newly created arrays. In this case, you can use Array.pus().apply(arr1,arr2) to create a new array instead. 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];
Convert NodeList to an array
If you run the document.querySelectorAll("p") function, it may return an array of DOM elements, that is, the NodeList object. But this object does not have the function functions of arrays, such as sort(), reduce(), map(), filter(), etc. In order for these native array function functions to be used on them, the node list needs to be converted into an array. You can use [].slice.call(elements) to implement:
var elements = document.querySelectorAll("p"); // NodeListvar arrayElements = [].slice.call(elements); // Now the NodeList is an arrayvar arrayElements = Array.from(elements); // This is another way of converting NodeList to ArrayShrinking of array elements
For the shuffle of array elements, there is no need to use any external libraries, such as Lodash, just do this:
var list = [1,2,3];console.log(list.sort(function() { Math.random() - 0.5 })); // [2,1,3]Summarize
Now you have learned some useful JavaScript tips. I hope these tips can help you solve some troubles at work, or this article will be helpful to you. If you have some excellent JavaScript tips, please share them with us in the comments.
The above 12 very practical JavaScript tips [Recommended] are all the content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.