Use the !! operator to convert a Boolean value
Sometimes we need to check whether a variable exists or check whether the value has a valid value, and return a true value if it exists. In order to do such verification, we can use the !! operator, which is very convenient and simple. You can use !!variable to detect variables. 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.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 the value of account.cash is greater than 0, the value returned by account.hasMoney is true.
Use + to convert strings into numbers
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 NaN will be returned, 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, in this case, it will return the timestamp number:
console.log(+new Date()) // 1461288164385
And conditional character
If you have a piece of code like this:
if (conected) { login(); }
You can also abbreviate variables and use && to connect them with functions, such as the above Example, can be abbreviated like this:
conected && login();
If some properties or functions exist in an object, you can also do this detection, as shown in the following code:
user && user.login();
Use The || operator
has the feature of default parameters in ES6. To emulate this feature in older browsers, use the || operator and pass the default value as the second argument. If the first parameter returns false, the second value will be considered a default value. Take 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 array.length in a loop
This technique is very simple, but when processing a large array loop, the impact on performance will be very large. Basically, everyone will write an array that iterates synchronously like this:
for(var i = 0; i < array.length; i++) { console.log(array[i]); }
If it is a small array, this is fine. If you are dealing with a large array, this code will iterate on each iteration. The array size will all be recalculated, which will cause some delays. In order to avoid this phenomenon, you can make a cache of array.length:
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 the attributes in the object
This little trick is useful when you need to detect the existence of some properties and avoid running undefined functions or properties. You might also want to use this trick if you plan to customize some cross-browser code. For example, you want to use document.querySelector() to select an id and make it compatible with the IE6 browser, but this function does not exist in the IE6 browser, so it is difficult to use this operator to detect whether the function exists. Very useful, as in 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 docuemnt.getElementById("id") will be 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 value of the array will be used 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. 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 size of the array. 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 the first five elements, you can truncate the array by array.length=5. 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
The String.replace() function allows you to use strings or regular expressions to replace strings. This function itself only Replace the first occurrence of the string, but you can use /g in the regular expression 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 If you want to merge two arrays, generally you will 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) instead to create 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];
Convert NodeList into an array
If you run the document.querySelectorAll("p") function, it may return an array of DOM elements, which is a NodeList object. But this object does not have the functions of an array, such as sort(), reduce(), map(), filter(), etc. In order for these native array functions to be used on it, the node list needs to be converted into an array. You can use [].slice.call(elements) to achieve:
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, there is no need to use any external For libraries, such as Lodash, just do this:
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 tricks. I hope these tips can help you solve some troubles at work, or that this article has been helpful to you. If you have some great JavaScript tips, please share them with us in the comments.

去掉重复并排序的方法:1、使用“Array.from(new Set(arr))”或者“[…new Set(arr)]”语句,去掉数组中的重复元素,返回去重后的新数组;2、利用sort()对去重数组进行排序,语法“去重数组.sort()”。

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于Symbol类型、隐藏属性及全局注册表的相关问题,包括了Symbol类型的描述、Symbol不会隐式转字符串等问题,下面一起来看一下,希望对大家有帮助。

怎么制作文字轮播与图片轮播?大家第一想到的是不是利用js,其实利用纯CSS也能实现文字轮播与图片轮播,下面来看看实现方法,希望对大家有所帮助!

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于对象的构造函数和new操作符,构造函数是所有对象的成员方法中,最早被调用的那个,下面一起来看一下吧,希望对大家有帮助。

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于面向对象的相关问题,包括了属性描述符、数据描述符、存取描述符等等内容,下面一起来看一下,希望对大家有帮助。

方法:1、利用“点击元素对象.unbind("click");”方法,该方法可以移除被选元素的事件处理程序;2、利用“点击元素对象.off("click");”方法,该方法可以移除通过on()方法添加的事件处理程序。

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于BOM操作的相关问题,包括了window对象的常见事件、JavaScript执行机制等等相关内容,下面一起来看一下,希望对大家有帮助。

foreach不是es6的方法。foreach是es3中一个遍历数组的方法,可以调用数组的每个元素,并将元素传给回调函数进行处理,语法“array.forEach(function(当前元素,索引,数组){...})”;该方法不处理空数组。


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Dreamweaver CS6
Visual web development tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment
