[Turn] 12 JavaScript Skills

Convert Boolean Values ​​Using !!Operators

Sometimes we need to check if a variable exists or if the value has a valid value, and return the truevalue if it exists. In order to do such verification, we can use !!the operator to achieve it is very convenient and simple. For variables, it can be used !!variablefor detection, as long as the value of the variable is: 0, null, " ", undefinedor NaNboth will return yes false, and vice versa 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.cashthe value is greater than 0, then account.hasMoneythe value returned is true.

+Convert strings to numbers using

This trick is very useful, it is very simple to convert string data to numbers, but it only works 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 works Date, in this case it will return timestamp numbers:

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

and conditional

If you have a piece of code like this:

if (conected) {
    login();
}

You can also abbreviate variables &&and connect them with functions, such as the example above, which can be abbreviated like this:

conected && login();

You can also detect if some property or function exists in an object, as shown in the following code:

user && user.login();

use ||operator

There is a default parameter feature in ES6. To emulate this feature in older browsers, you can use ||the operator and pass the default value as the second parameter. If the first parameter returns a value false, then the second value will be considered a default value. Such as 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 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 in looparray.length

The trick is simple, and the performance hit is huge when looping through a large array. Basically, everyone writes an array that iterates synchronously like this:

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

This works fine if it's a small array, but if you're dealing with a large array, this code will recalculate the size of the array on each iteration, which will cause some delays. In order to avoid this phenomenon, you can array.lengthdo 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 little trick is useful when you need to detect the existence of some properties and avoid running undefined functions or properties. You may also use this little trick if you plan to code some cross-compatible browsers. For example, you want to use document.querySelector()to select one idand make it compatible with IE6 browser, but this function does not exist in IE6 browser, then it is very useful to use this operator to detect whether this function exists, as follows Example:

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

In this example, if the function documentdoes not exist querySelector, it will be called docuemnt.getElementById("id").

Get the last element in an array

Array.prototype.slice(begin,end)Used to get the array elements between and begin. endIf you don't set endthe parameter, the default length of the array will be used as the endvalue. But some students may not know that this function can also accept negative values ​​as parameters. If you set a negative value as beginthe value of , then 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 the array, if it is used to delete some elements in the array, it is very useful. For example, if your array has 10one element, but you only want the first five elements, then you can array.length=5truncate the array by . Such as the following 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

String.replace()The function allows you to use strings or regular expressions to replace strings. This function itself only replaces the first occurrence of the string, but you can use regular expressions /gto 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 combine two arrays, you will generally use a 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 will consume a lot of memory to store the newly created array. In one of these cases, you can use Array.pus().apply(arr1,arr2)instead of creating a new array. This method is not used to create a new array, it just merges the first and second arrays 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];

will NodeListconvert to array

If you run document.querySelectorAll(“p”)the function, it may return an array of DOM elements, aka NodeListobjects. But this object does not have the functional capabilities of arrays, such as sort(), reduce(), map(), filter()etc. In order for these native array functions to work on it, the node list needs to be converted to an array. This can [].slice.call(elements)be achieved using:

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, you don't need to use any external library like Lodash, just do:

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

Summarize

Now you have learned some useful JavaScript tricks. Hope these little tips can help you out of some troubles at work, or that this article is helpful to you. If you have some great JavaScript tips, please share them with us in the comments.

Copyright belongs to the author.
For commercial reprints, please contact the author for authorization, and for non-commercial reprints, please indicate the source.
Original:  http://www.w3cplus.com/javascript/12-extremely-useful-hacks-for-javascript.html?f=tt  ©  w3cplus.com

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327038055&siteId=291194637