This article mainly introduces the relevant information collected by the JavaScript tips. For more information, please refer to them and hope to provide you with these short and practical JavaScript skills to improve your programming skills. This article mainly introduces the relevant information collected by the JavaScript tips. For more information, please refer to them and hope to provide you with these short and practical JavaScript skills to improve your programming skills.
Use !! Operator to convert boolean values
Sometimes we need to check whether a variable exists or whether the value has a valid value. If so, true is returned. For such verification, we can use it !! Operators are very convenient and simple to implement. You can use variables !! Variable checks. If the value of a variable is 0, null, "", undefined, Or NaN, false is returned, and true is returned. 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 example, if the value of account. cash is greater than 0, the value returned by account. hasMoney is true.
Use + to convert a string to a number
This technique is very useful. It is very simple and can convert string data into numbers. However, it is only applicable to string data. Otherwise, NaN is returned, for example:
function toNumber(strNumber) { return +strNumber;}console.log(toNumber("1234")); // 1234console.log(toNumber("ACB")); // NaN
This applies to Date. In this example, it returns a 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 connect them with functions. 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 the | Operator and pass the default value as the second parameter. If the value returned by the first parameter is false, 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 array. length in a loop
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 problem, you can cache array. length as follows:
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 example, you want to use document. querySelector () to select an id and make it compatible with the IE 6 browser. However, this function does not exist in the IE 6 browser, it is very useful to use this operator to check whether the function exists, as shown in the following example:
if ('querySelector' in document) { document.querySelector("#id");} else { document.getElementById("id");}
In this example, if the document does not have the querySelector function, docuemnt. getElementById ("id") is called ").
Obtain 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 is treated as the end value. However, some users may not know that this function can accept negative values as parameters. If you set a negative value as the value of begin, you can obtain 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, if your array has 10 elements, but you only want to use the first five elements, you can use 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. the replace () function allows you to use a string or regular expression to replace a string. This function only replaces the string that appears for the first time. However, you can use the/g in many regular expressions to simulate 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 will consume a lot of memory to store the newly created array. In this case, you can use Array. 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];
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. However, this object does not have array functions, such as sort (), reduce (), map (), and filter. To enable these native array functions to be used on them, you need to convert the node list to 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 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]
A more way to convert a value
It is very common to convert a string to a number. The simplest and fastest (jspref) method is to use the + (plus) algorithm.
var one = '1';var numberOne = +one; // Number 1
You can also use the-(minus sign) algorithm to convert the conversion type to a negative value.
var one = '1';var negativeNumberOne = -one; // Number -1
Functions of returned objects can be used for chained operations.
When you create a function of an object-oriented JavaScript Object, the function returns an object that can be chained and executed together.
function Person(name) {this.name = name;this.sayName = function() {console.log("Hello my name is: ", this.name);return this;};this.changeName = function(name) {this.name = name;return this;};}var person = new Person("John");person.sayName().changeName("Timmy").sayName();//Hello my name is: John//Hello my name is: Timmy
Passing parameters to the callback function
By default, you cannot pass parameters to the callback function, as shown below:
function callback() {console.log('Hi human');}document.getElementById('someelem').addEventListener('click', callback);
You can use the advantages of JavaScript closure to pass parameters to the callback function. The example is as follows:
function callback(a, b) {return function() {console.log('sum = ', (a+b));}}var x = 1, y = 2;document.getElementById('someelem').addEventListener('click', callback(x, y));
What is a closure? A closure is a function for independent (free) variables. In other words, the function defined in the closure will remember the environment it was created. For more information, see MDN. Therefore, when called, The X/Y parameter exists in the scope of the callback function.
Another method is to use the binding method. For example:
var alertText = function(text) {alert(text);};document.getElementById('someelem').addEventListener('click', alertText.bind(this, 'hello'));
Upgrade
Understanding Ascension will help you organize your function. You only need to remember that the variable declaration and definition function will be promoted to the top. The definition of a variable does not exist, even if you declare and define a variable in the same line. In addition, the variable declaration let the system know that the variable exists, and the definition is to assign it to it.
Function doTheThing () {// error: notDeclared is not definedconsole. log (notDeclared); // output: undefinedconsole. log (definedLater); var definedLater; definedLater = 'I am defined! '// Output:' I am defined! 'Console. log (definedLater) // Outputs: undefinedconsole. log (definedSimulateneously); var definedSimulateneously = 'I am defined! '// Output:' I am defined! 'Console. log (definedSimulateneously) // output: 'I did it! 'Dosomethingelse (); function doSomethingElse () {console. log ('I did it! ');} // Error: undefined is not a functionfunctionVar (); var functionVar = function () {console. log (' I did it! ');}}
To make things easier to read, the declaration of raising a variable within the function scope will let you know which scope the variable declaration comes from. Define variables before you need them. Define the function at the bottom of the scope to ensure the code is clear and standardized.
I hope these tips can help you solve some problems at work and help you.