Home Web Front-end JS Tutorial Sharing the 12 most practical skills in JavaScript

Sharing the 12 most practical skills in JavaScript

May 22, 2017 am 11:42 AM

In this article, I will share 12 very useful JavaScript tips. These tips can help you reduce and optimize your code. Friends in need can refer to this article

In this article, I will share 12 very useful JavaScript tips. These tips can help you reduce and optimize your code.

1) Use !! to convert variable into Boolean type

Sometimes, we need to check whether some variables exist , or if it has a valid value, thus treating their value as true. For doing such a check you can use || (double negation operator) which automatically converts any type of data to boolean, only these variables will return false: 0, null, "", undefined or NaN, others return true. Let's take a look at this simple 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
Copy after login

In this example, if the value of account.cash is greater than zero, the value of account.hasMoney is true.

2) Use + to convert variables into numbers

This conversion is super simple, but it only works with numbers strings , otherwise it will Returns NaN (not a number). Take a look at this example:

function toNumber(strNumber) { 
 return +strNumber; 
} 
console.log(toNumber("1234")); // 1234 
console.log(toNumber("ACB")); // NaN
Copy after login

This conversion operation can also be applied to Date, in which case it will return Timestamp:

console.log(+new Date()) // 1461288164385
Copy after login

3) Short-circuit condition

If you have seen this kind of code:

if (conected) { 
 login(); 
}
Copy after login

Then you can use && (AND between these two variables operator) to shorten the code. For example, the previous code can be reduced to one line:

conected && login();
Copy after login

You can also use this method to check whether certain properties or functions exist in the object . Similar to the following code:

user && user.login();
Copy after login

4) Use || to set the default value

There is a default parameter function in ES6. To emulate this functionality in older browsers, you can use || (OR operator) and pass the default value as its second argument. If the first parameter returns false, the second parameter will be returned as the default value. Look at this 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
Copy after login

5) cachingarray.length## in loop

#This trick is very simple and avoids a huge impact on performance when looping through large

arrays. Basically this is how almost everyone uses for to loop through an array:

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

If you're working with smaller arrays, that's fine, but if you're dealing with large arrays, this is The code will repeatedly calculate the size of the array in each loop, which will cause a certain delay. To avoid this, you can cache array.length in a variable so that the cache is used instead of array.length each time in the loop:

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

For more conciseness, you can write:

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

6) Detect properties in objects

This technique is very useful when you need to check whether certain properties exist and avoid running undefined functions or properties. You might also use this technique if you plan to write cross-browser code. For example, let's assume you need to write code that is compatible with older versions of Internet Explorer 6 and want to use

document.querySelector() to get certain elements by ID. However, in modern browsers, this function does not exist. So, to check if this function exists, you can use the in operator. Take a look at this example:

if (&#39;querySelector&#39; in document) { 
 document.querySelector("#id"); 
} else { 
 document.getElementById("id"); 
}
Copy after login

In this case, if there is no querySelector function in the document, it will use document.getElementById() instead.

7) Get the last element of the array

Array.prototype.slice(begin,

end) can be used to clip the array. But if the value of the end parameter end is not set, the function will automatically set end to the array length value. I think few people know that this function can accept negative values. If you set begin to a negative number, you can get the reciprocal element from the array:

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]
Copy after login

8) Array truncation

这个技术可以锁定数组的大小,这对于要删除数组中固定数量的元素是非常有用的。例如,如果你有一个包含10个元素的数组,但是你只想获得前五个元素,则可以通过设置array.length = 5来阶段数组。看下这个例子:

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]
Copy after login

9) 全部替换

String.replace()函数允许使用String和Regex来替换字符串,这个函数本身只能替换第一个匹配的串。但是你可以在正则表达式末尾添加/g来模拟replaceAll()函数:

var string = "john john"; 
console.log(string.replace(/hn/, "ana")); // "joana john" 
console.log(string.replace(/hn/g, "ana")); // "joana joana"
Copy after login

10) 合并数组

如果你需要合并两个数组,你可以使用Array.concat()函数:

var array1 = [1, 2, 3]; 
var array2 = [4, 5, 6]; 
console.log(array1.concat(array2)); // [1,2,3,4,5,6];
Copy after login

但是,这个函数对于大数组来说不并合适,因为它将会创建一个新的数组并消耗大量的内存。在这种情况下,你可以使用Array.push.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];
Copy after login

11) 把NodeList转换成数组

如果运行document.querySelectorAll("p")函数,它会返回一个DOM元素数组,即NodeList对象。但是这个对象并没有一些属于数组的函数,例如:sort(),reduce(),map(),filter()。为了启用这些函数,以及数组的其他的原生函数,你需要将NodeList转换为数组。要进行转换,只需使用这个函数:[] .slice.call(elements):

var elements = document.querySelectorAll("p"); // NodeList  
var arrayElements = [].slice.call(elements); // 现在已经转换成数组了 
var arrayElements = Array.from(elements); // 把NodeList转换成数组的另外一个方法
Copy after login

12) 对数组元素进行洗牌

如果要像外部库Lodash那样对数据元素重新洗牌,只需使用这个技巧:

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

结论

现在,你已经学到了一些有用的JS技巧,它们主要用于缩减JavaScript代码量,其中一些技巧在许多流行的JS框架都使用到,如Lodash,Underscore.js,Strings.js等。如果你知道其他JS技巧,欢迎分享!

【相关推荐】

1. Javascript免费视频教程

2. JavaScript运动框架之多值运动的具体介绍(四)

3. JavaScript运动框架之多物体任意值运动的示例代码分享(三)

4. JavaScript运动框架之如何解决防抖动问题、悬浮对联(二)

5. JavaScript运动框架之如何解决速度正负取整问题(一)

The above is the detailed content of Sharing the 12 most practical skills in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Win11 Tips Sharing: Skip Microsoft Account Login with One Trick Win11 Tips Sharing: Skip Microsoft Account Login with One Trick Mar 27, 2024 pm 02:57 PM

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

A must-have for veterans: Tips and precautions for * and & in C language A must-have for veterans: Tips and precautions for * and & in C language Apr 04, 2024 am 08:21 AM

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.

What are the tips for novices to create forms? What are the tips for novices to create forms? Mar 21, 2024 am 09:11 AM

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 Getting Started Guide: A must-read for beginners to quickly master usage skills! VSCode Getting Started Guide: A must-read for beginners to quickly master usage skills! Mar 26, 2024 am 08:21 AM

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

PHP programming skills: How to jump to the web page within 3 seconds PHP programming skills: How to jump to the web page within 3 seconds Mar 24, 2024 am 09:18 AM

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

Win11 Tricks Revealed: How to Bypass Microsoft Account Login Win11 Tricks Revealed: How to Bypass Microsoft Account Login Mar 27, 2024 pm 07:57 PM

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.

Tips for using Laravel form classes: ways to improve efficiency Tips for using Laravel form classes: ways to improve efficiency Mar 11, 2024 pm 12:51 PM

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-depth understanding of function refactoring techniques in Go language In-depth understanding of function refactoring techniques in Go language Mar 28, 2024 pm 03:05 PM

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

See all articles