12 very useful JavaScript tips and javascript tips
In this article, I will share with you 12 tips on JavaScript. These tips may help you solve some problems in your actual work.
Use
!!
Operator to convert boolean values
Sometimes we need to check whether a variable exists or whether the value has a valid value.true
Value. For such verification, we can use!!
Operators are very convenient and simple to implement. You can use!!variable
For detection, as long as the value of the variable is:0
,null
," "
,undefined
OrNaN
Will returnfalse
Otherwisetrue
. For 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); // false
In this exampleaccount.cash
The value is greater0
, Thenaccount.hasMoney
The returned value istrue
.
Use
+
Converts a string to a number.
This technique is very useful. It is very simple. It can convert string data into numbers, but it is only suitable for string data. Otherwise, it will returnNaN
For example:
function toNumber(strNumber) { return +strNumber;}console.log(toNumber("1234")); // 1234console.log(toNumber("ACB")); // NaN
This also appliesDate
In this example, it returns the timestamp Number:
console.log(+new Date()) // 1461288164385
And condition character
If you have a piece of code like this:
if (conected) { login();}
You can also abbreviated variables and use&&
It is connected with a function. For example, the preceding example can be abbreviated as follows:
conected && login();
If some attributes or functions exist in an object, you can check them as follows:
user && user.login();
Use
||
Operator
ES6 has the default parameter feature. To simulate this feature in earlier browsers, you can use||
And pass the default value as the second parameter. If the value returned by the first parameter isfalse
The second value is considered as a default value. For 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); // 25
Cache in Loop
array.length
This technique is very simple. when processing a large array loop, it will have a very huge impact on performance. Basically, everyone will write an array of such synchronization iterations:
for(var i = 0; i < array.length; i++) { console.log(array[i]);}
This is good if it is a small array. If you want to process a large array, this code recalculates the array size in each iteration, this will cause some delays. To avoid this phenomenon, you canarray.length
Make 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]);}
Property in the detection object
This tip is useful when you need to check whether some attributes exist to avoid running undefined functions or attributes. If you plan to develop cross-compatible browser code, you may also use this tip. For exampledocument.querySelector()
To selectid
And make it compatible with the IE 6 browser, but this function does not exist in the IE 6 browser, it is very useful to use this operator to check whether this function exists, as shown in the following example:
if ('querySelector' in document) { document.querySelector("#id");} else { document.getElementById("id");}
In this example, ifdocument
Does not existquerySelector
Function, then it will calldocuemnt.getElementById("id")
.
Obtain the last element in the array.
Array.prototype.slice(begin,end)
Used to obtainbegin
Andend
. If you do not setend
Parameter, the default Length Value of the array is treatedend
Value. However, some users may not know that this function can accept negative values as parameters. If you set a negative valuebegin
Then you can get the last element of the array. For example:
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 tip is mainly used to lock the array size. It is very useful if it is used to delete some elements in the array. For example, your array has10
But you only want to use the first five elements.array.length=5
To truncate the array. For 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
String.replace()
The function allows you to use a string or regular expression to replace a string. In itself, this function only replaces the string that appears for the first time. However, you can use regular expressions to express multiple/g
To simulatereplaceAll()
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 useArray.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 this case, you can useArray.pus().apply(arr1,arr2)
To create a new array. This method is not used to create a new array, but to combine the first and second numbers and reduce the 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];
Set
NodeList
Convert to array
If you rundocument.querySelectorAll(“p”)
Function, it may return an array of DOM elements, that isNodeList
Object. However, this object does not have array functions, suchsort()
,reduce()
,map()
,filter()
. To enable these native array functions to be used on them, you need to convert the node list to an array. Available[].slice.call(elements)
To achieve:
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 Array
Shuffling array elements
You do not need to use any external libraries for shuffling array elements, such as Lodash:
var list = [1,2,3];console.log(list.sort(function() { Math.random() - 0.5 })); // [2,1,3]
Summary
Now you have learned some useful JavaScript tips. I hope these tips can help you solve some problems at work, or this article will help you. If you have some excellent JavaScript tips, please share them with us in your comments.
[I have a QQ Group for front-end learning and communication: 328058344 if you encounter any problems during the process of learning the front-end, please come to my QQ Group to ask questions. The group will update some learning resources every day. Chat is prohibited .]