You may be new to JavaScript, or may have only used it occasionally. Regardless, JavaScript has changed a lot, and some features are well worth using. This article introduces some features that, in my opinion, a serious JavaScript developer will use at some point every day.
References
The following two sites about ES6+ are my favorites:
Expand operator
As the name suggests, it is used as an expansion operator (...) before an object or array to expand a structure for a list. Demonstrate:
let firstHalf = [ 'one', 'two']; let secondHalf = ['three', 'four', ...firstHalf];
Is this writing method elegant and concise enough? If the spread operator is not used, we have to write like this:
let firstHalf = [ 'one', 'two']; let secondHalf = ['three', 'four']; for(var i=0, i <firstHalf.length; i++ ) { secondHalf.push(firstHalf[i]); }
The spread operator is also suitable for merging the properties of objects:
const hero = { name: 'Xena - Warrior Princess', realName: 'Lucy Lawless' } const heroWithSword = { ...hero, weapon: 'sword' }
If the spread operator is not used, you need to traverse the objects Attributes:
let keys = Object.keys(hero); let obj = {}; for(var i=0; i< keys.length; i++) { obj[keys[i]] = keys[props[i]]; }
Remaining parameters
Remaining parameters will be included in the sequence. The characteristic of JavaScript is that the number of parameters is very flexible. There is usually an arguments variable collecting the arguments. Let's look at an example:
function add(first, second, ...remaining) { return first + second; }
The above piece of code only adds first and second, that is, calling add(1, 2) and add(1, 2, 3, 4) will Got the same result. Let's correct it below:
function add(first, second, ...remaining) { return first + second + remaining.reduce((acc, curr) => acc + curr, 0); }
As mentioned before, ...remaining collects the remaining parameters and provides us with a naming of these parameters, making it clear that we intend to handle the remaining parameters. I remember that ES5 already has arguments at the latest, but few people know about it.
String interpolation
Have you ever seen such a statement?
class Product { constructor(name, description, price) { this.name = name; this.description = description; this.price = price; } getDescription() { return " Full description \n" + " name: " + this.name + " description: " + this.description } }
Of course, I’m referring to the long, unreadable multi-line statement in the getDescription() method. A similar phenomenon exists in most programming languages. Several languages provide string interpolation, and luckily, JavaScript is one of them. Let’s rewrite the getDescription() method:
getDescription() { return `Full description \n: name: ${this.name} description ${this.description} `; }
${} interpolation can be used in a pair of `-wrapped strings. It looks much more comfortable now.
Abbreviation attribute
must be written like this in ES5:
function createCoord(x, y) { return { x: x, y: y } }
ES6 can use abbreviation attribute in the future:
function createCoord(x, y) { return { x, y } }
It looks more refreshing Already?
Method attribute
Method attribute is an attribute defined in the object that points to a method. Consider the following piece of ES5 code as an example:
const math = { add: function(a,b) { return a + b; }, sub: function(a,b) { return a - b; }, multiply: function(a,b) { return a * b; } }
ES6 will only need to write this in the future:
const math = { add(a,b) { return a + b; }, sub(a,b) { return a - b; }, multiply(a,b) { return a * b; } }
Destructuring assignment
Destructuring assignment is good for the developer's psychology healthy.
Consider the following code:
function handle(req, res) { const name = req.body.name; const description = req.body.description; const url = req.url; log('url endpoint', url); // 大量代码逻辑 dbService.createPerson(name, description) }
No matter from any point of view, the above code is not perfect, but it does reflect an application scenario where we want to start from the object. Obtain data at different levels. You may ask, what's the problem here? Well, I can save myself some keystrokes by not declaring so many variables.
function handle(req, res) { const { body: { name, description }, url } = req; log('url endpoint', url); // 大量代码逻辑 dbService.createPerson(name, description)
Look, our above code compresses three lines into one.
Destructuring assignment is not limited to objects. It works equally well with arrays. Consider the following code:
const array = [1,2,3,4,5,6]; const a = array[0]; const c = array[2];
The above code can be rewritten in a more elegant way:
const array = [1,2,3,4,5,6]; const [a, ,c, ...remaining] = arr; // remaining = [4,5,6]
We can use the above pattern matching to decompose the values of the array. We use , , to skip certain values. The remaining parameters mentioned above can also be used here. Here we capture the remaining array members through the remaining parameters.
Destructuring assignment can also be used for functions and parameters. When a function has more than 2-3 parameters, it is a de facto standard in JavaScript to use an object to collect all parameters. For example, the following function:
function doSomething(config) { if(config.a) { ... } if(config.b) { ... } if(config.c) { ... } }
has a better way of writing:
function doSomething({ a, b, c }) { if(a) { ... } if(b) { ... } if(c) { ... } }
Array methods
ES6 introduces many useful array methods, such as:
- find(), find the member in the list, return null means not found
- findIndex(), find the index of the list member
- some(), check some Whether an assertion is true on at least one member of the list
- includes, whether the list contains an item
The following code will help you understand their usage:
const array = [{ id: 1, checked: true }, { id: 2 }]; arr.find(item => item.id === 2) // { id: 2 } arr.findIndex(item => item.id === 2) // 1 arr.some(item => item.checked) // true const numberArray = [1,2,3,4]; numberArray.includes(2) // true
Promises + Async/Await
If you have been in this circle for a few years, you may remember that there was a time when we only had callbacks, like this:
function doSomething(cb) { setTimeout(() => { cb('done') }, 3000) } doSomething((arg) => { console.log('done here', arg); })
We use callbacks because some operations are asynchronous and take time to complete. Then we got the promise library and people started using it. Then JavaScript gradually added native support for promises.
function doSomething() { return new Promise((resolve, reject) => { setTimeout(() => { resolve('done') }, 3000) }) } doSomething().then(arg => { console.log('done here', arg); })
We can even call it like this to string promises together:
getUser() .then(getOrderByUser) .then(getOrderItemsByOrder) .then(orderItems => { // 处理排序后的成员 })
Later, life will be better, we have async/await, the above code can be written like this:
async function getItems() { try { const user = await getUser(); const order = await getOrderByUser(user); const items = await getOrderItemsByOrder(order); return items; } catch(err) { // 在这里处理错误,建议返回某个值或者重新抛出错误 } } getItems().then(items => { // 处理排序后的成员 })
Module
Almost any programming language supports the concept of module, which is to divide the code into multiple files, each file is a self-contained unit (module). Consider the following code:
// math.js export function add(a,b) { return a + b; } export function sub(a,b) { return a - b; } export default mult(a,b) => a * b; // main.js import mult, { add, sub } from './math'; mult(2, 4) // 8 add(1,1) // 2 sub(1,2) // -1
我们在上面用 export 关键字注明了 add 和 sub 这两个结构对任何引入该模块的模块都公开可见。 export default 关键字则注明仅仅 import 模块时得到的结构。 在 main.js 中,我们将导入的 default 命名为 mult,同时指明我们引入 add() 和 sub() 这两个方法。
箭头函数和字典作用域 this
我在这篇文章中很多地方都用到了箭头函数,它不过是另一种函数表示法。 过去我们只能这么声明函数:
function printArray(arr) { // 具体操作 }
现在我们也可以这么写:
const printArray = (arr) => { // 具体操作 }
我们也可以将函数声明写到一行里:
const add = (a,b) => a + b
上面的代码表明我们进行操作并返回结果。 我们也可以采用下面的语法返回一个对象:
const create = (a,b) = > ({ x: a, y: b })
过去会碰到搞不清 this 是什么的问题。 考虑下面的代码:
let array = [1,2,3]; function sum() { this.total = 0; arr.forEach(function(item) { this.total+= item; // 糟糕,`this` 是内层函数的 `this` }) return total; }
上面代码中的 this 指向 forEach 内部函数的 this,这可不是我们想要的。 过去我们通过以下方式解决这个问题:
function sum() { this.total = 0; var self = this; arr.forEach(function(item) { self.total+= item; // 这里我们使用 `self`,它能解决问题,但是感觉有点别扭 }) return total; }
箭头函数可以解决问题,再也不用 self 了,现在代码看起来是这样的:
function sum() { this.total = 0; arr.forEach((item) => { this.total+= item; // 一切安好,`this` 指向外层函数 }) return total; }
大胜!
结语
我还可以讲讲更多 ES6 方面的内容,不过这篇文章中我只打算介绍我最偏爱的特性。 我觉得你应该从今天开始使用这些特性。
相关免费学习推荐:js视频教程
The above is the detailed content of 10 very useful JavaScript features. For more information, please follow other related articles on the PHP Chinese website!

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.


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

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Chinese version
Chinese version, very easy to use

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Zend Studio 13.0.1
Powerful PHP integrated development environment

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool
