12 Essential JavaScript Tips
In this article, I will share with you 12 tips about JavaScript. These tips may help you solve some problems in your actual work.
Related learning recommendations: javascript video tutorial
Use !!
operator to convert Boolean value
Sometimes we need to check whether a variable exists or check whether the value has a valid value. If it exists, return the true
value. In order to do such verification, we can use the !!
operator, which 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
will return false
, otherwise true
will be returned. 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
, then account.hasMoney
returns The value is true
.
Use
Convert strings to numbers
This technique is very useful. It is very simple and can convert string data into numbers, but it is only suitable for characters. 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 Numbers:
console.log(+new Date()) // 1461288164385
and conditionals
If you have a piece of code like this:
if (conected) { login(); }
You can also abbreviate the variables and use &&
and Functions connected together, like the example above, 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 ||
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 parameter. If the value returned by the first parameter is 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 the looparray.length
This technique is very simple. This has an impact on performance when processing a large array loop. will be very big. Basically, everyone will write an array that synchronizes iteration 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 IE6 browser, but this function does not exist in IE6 browser, then It is very useful to use this operator to detect whether the function exists, as in the following example:
if ('querySelector' in document) { document.querySelector("#id"); } else { document.getElementById("id"); }
In this example, if document
does not existquerySelector
function, then docuemnt.getElementById("id")
will be called.
Get the last element in the array
Array.prototype.slice(begin,end)
is used to get begin
and end# Array elements between ##. 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]
10 elements, but you only want the first five elements, then 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]
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 the
/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"
Array.concat() function:
var array1 = [1,2,3]; var array2 = [4,5,6]; console.log(array1.concat(array2)); // [1,2,3,4,5,6];
然后这个函数并不适合用来合并两个大型的数组,因为其将消耗大量的内存来存储新创建的数组。在这种情况之个,可以使用Array.pus().apply(arr1,arr2)
来替代创建一个新数组。这种方法不是用来创建一个新的数组,其只是将第一个第二个数组合并在一起,同时减少内存的使用:
var array1 = [1,2,3]; var array2 = [4,5,6]; console.log(array1.push.apply(array1, array2)); // [1,2,3,4,5,6];
将NodeList
转换成数组
如果你运行document.querySelectorAll(“p”)
函数时,它可能返回DOM元素的数组,也就是NodeList
对象。但这个对象不具有数组的函数功能,比如sort()
、reduce()
、map()
、filter()
等。为了让这些原生的数组函数功能也能用于其上面,需要将节点列表转换成数组。可以使用[].slice.call(elements)
来实现:
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
数组元素的洗牌
对于数组元素的洗牌,不需要使用任何外部的库,比如Lodash,只要这样做:
var list = [1,2,3]; console.log(list.sort(function() { Math.random() - 0.5 })); // [2,1,3]
总结
现在你学会了些有用的JavaScript小技巧。希望这些小技巧能在工作中帮助你解决一些麻烦,或者说这篇文章对你有所帮助。如果你有一些优秀的JavaScript小技巧,欢迎在评论中与我们一起分享。
The above is the detailed content of 12 Essential JavaScript Tips. For more information, please follow other related articles on the PHP Chinese website!

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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Win11 Tips Sharing: One trick to skip Microsoft account login Windows 11 is the latest operating system launched by Microsoft, with a new design style and many practical functions. However, for some users, having to log in to their Microsoft account every time they boot up the system can be a bit annoying. If you are one of them, you might as well try the following tips, which will allow you to skip logging in with a Microsoft account and enter the desktop interface directly. First, we need to create a local account in the system to log in instead of a Microsoft account. The advantage of doing this is

In C language, it represents a pointer, which stores the address of other variables; & represents the address operator, which returns the memory address of a variable. Tips for using pointers include defining pointers, dereferencing pointers, and ensuring that pointers point to valid addresses; tips for using address operators & include obtaining variable addresses, and returning the address of the first element of the array when obtaining the address of an array element. A practical example demonstrating the use of pointer and address operators to reverse a string.

We often create and edit tables in excel, but as a novice who has just come into contact with the software, how to use excel to create tables is not as easy as it is for us. Below, we will conduct some drills on some steps of table creation that novices, that is, beginners, need to master. We hope it will be helpful to those in need. A sample form for beginners is shown below: Let’s see how to complete it! 1. There are two methods to create a new excel document. You can right-click the mouse on a blank location on the [Desktop] - [New] - [xls] file. You can also [Start]-[All Programs]-[Microsoft Office]-[Microsoft Excel 20**] 2. Double-click our new ex

VSCode (Visual Studio Code) is an open source code editor developed by Microsoft. It has powerful functions and rich plug-in support, making it one of the preferred tools for developers. This article will provide an introductory guide for beginners to help them quickly master the skills of using VSCode. In this article, we will introduce how to install VSCode, basic editing operations, shortcut keys, plug-in installation, etc., and provide readers with specific code examples. 1. Install VSCode first, we need

Win11 tricks revealed: How to bypass Microsoft account login Recently, Microsoft launched a new operating system Windows11, which has attracted widespread attention. Compared with previous versions, Windows 11 has made many new adjustments in terms of interface design and functional improvements, but it has also caused some controversy. The most eye-catching point is that it forces users to log in to the system with a Microsoft account. For some users, they may be more accustomed to logging in with a local account and are unwilling to bind their personal information to a Microsoft account.

Title: PHP Programming Tips: How to Jump to a Web Page within 3 Seconds In web development, we often encounter situations where we need to automatically jump to another page within a certain period of time. This article will introduce how to use PHP to implement programming techniques to jump to a page within 3 seconds, and provide specific code examples. First of all, the basic principle of page jump is realized through the Location field in the HTTP response header. By setting this field, the browser can automatically jump to the specified page. Below is a simple example demonstrating how to use P

Forms are an integral part of writing a website or application. Laravel, as a popular PHP framework, provides rich and powerful form classes, making form processing easier and more efficient. This article will introduce some tips on using Laravel form classes to help you improve development efficiency. The following explains in detail through specific code examples. Creating a form To create a form in Laravel, you first need to write the corresponding HTML form in the view. When working with forms, you can use Laravel

In Go language program development, function reconstruction skills are a very important part. By optimizing and refactoring functions, you can not only improve code quality and maintainability, but also improve program performance and readability. This article will delve into the function reconstruction techniques in the Go language, combined with specific code examples, to help readers better understand and apply these techniques. 1. Code example 1: Extract duplicate code fragments. In actual development, we often encounter reused code fragments. At this time, we can consider extracting the repeated code as an independent function to
