to deconstruct
Destructuring: is the process of breaking down a data structure into smaller parts. In ES6, extract values from arrays and objects, and assign values to variables.
So what is the use of deconstruction?
-
可以大大的简化变量声明操作。
// ES5
var foo = 1
var bar = 2
var baz = 3
// ES6
let [foo, bar, baz] = [1, 2, 3]
-
变量交换:看起来如同镜像。赋值语句的左侧的解构模式,右侧是临时创建的数组字面量。x 被赋值为数组中的 y,y 被赋值为数组中的 x。
let x = 1
let y = 2
;[x, y] = [y, x]
// x = 2, y = 1
-
对象解构
var obj = { x: 1, y: 2, c: 1 }
let { x, y } = obj
// x = 1
// y = 2
-
字符串解构
const [a, b, c, d, e] = hello
// a => h
// b => e
// c => l
// d => l
// e => o
-
函数参数解构
const xueyue = {
name: 雪月 ,
age: 18,
}
function getAge({ name, age }) {
return `${name}今年${age}岁`
}
getAge(xueyue) // 雪月今年18岁
arrow function
ES6
=>
Allows to define functions using arrows
var f = v => v
// 等同于 ES5 的
var f = function (v) {
return v
}
If the arrow function takes no parameters or requires multiple parameters, use parentheses to denote the parameter part.
var f = () => 5
// 等同于 ES5 的
var f = function () {
return 5
}
var sum = (numl, num2) => numl + num2
// 等同于 ES5 的
var sum = function (numl, num2) {
return numl + num2
}
Arrow functions can be used in conjunction with destructuring.
const full = ({ first , last }) => first + + last;
// 等同于 ES5 的
function full(person) {
return person.first + + person.last;
}
Arrow functions make expression more concise
const isEven = n => n % 2 === 0
const square = n => n * n
var result = values.sort((a, b) => a - b)
// 等同于 ES5 的
var result = values.sort(function (a, b) {
return a - b
})
The above code only uses two lines to define two simple utility functions. If you don't use arrow functions, it may take up multiple lines, and it's not as eye-catching as it is now.
Points to note when using arrow functions
-
The object in the function body
this
is the object where it is defined, not the object where it is used. -
Cannot be used as a constructor, that is,
new
commands cannot be used, otherwise an error will be thrown. -
Object cannot be used
arguments
, the object does not exist within the body of the function. If you want to use it, you can userest
parameters instead. -
Commands cannot be used
yield
, so arrow functions cannot be usedGenerator
as functions.
Among the above four points, the first point is particularly noteworthy. this
The pointing of the object is mutable, but in arrow functions, it is fixed.
// ES6
function foo() {
setTimeout(() => {
console.log( id: , this.id)
}, 100)
}
// 转换成ES5
function foo() {
var _this = this
setTimeout(function () {
console.log( id: , _this.id)
}, 100)
}
In the above code, the converted ES5
version clearly shows that the arrow function does not have its own at all this
, but refers to the outer layer this
.
template string
The template string ( template string ) is an enhanced version of the string,
(``)
marked with backticks. It can be used as a normal string, or it can be used to define multi-line strings, or to embed variables in strings.
const { log } = console
const name = 雪月
const age = 18
// 普通字符串拼接
const result = name + 今年 + age + 岁
// 使用模板字符串
const result2 = `${name}今年${age}岁`
log(result) // 雪月今年18岁
log(result2) // 雪月今年18岁
// ${} 大括号可以放入任意的 JavaScript 表达式,可以进行运算
const result3 = `${name}今年${age * 2}岁`
log(result3) // 雪月今年36岁
Remaining arguments/expansion syntax
ES6 introduces rest parameters (in the form of ...变量名
), which are used to get redundant parameters of functions, so that there is no need to use arguments
objects. rest
The argument collocation variable is an array into which the extra arguments are placed.
function sortNumbers() {
return Array.prototype.slice.call(arguments).sort()
}
// 使用 rest
const sortNumbers = (...numbers) => numbers.sort()
Comparing the above two ways of writing, we can find that rest
the way of writing parameters is more natural and concise.
The spread operator ( spread
) is three dots (...) as the rest
inverse operation of the parameters turns an array into a sequence of parameters separated by commas
console.log(...[1, 2, 3])
// 1 2 3
console.log(1, ...[2, 3, 4], 5)
// 1 2 3 4 5
apply
Here is a practical example of the spread operator substitution method Applied Math.max
method simplifies finding the largest element in an array.
// ESS 的写法
Math.max.apply(null, [14, 3, 77])
// ES6 的写法
Math.max(...[14, 3, 77])
// 等同于
Math.max(14, 3, 77)
The spread operator provides a new way to combine arrays.
// ESS
;[1, 2].concat(more)
// ES6
;[1, 2, ...more]
The object's spread operator (...) is used to take out all traversable properties of the parameter object and copy them to the current object.
let z = { a: 3, b: bb }
let n = { ...z }
n // { a: 3, b: bb }
n === z // false
Special attention: ...
extending the object can only be done when the object attribute is 基本数据类型
yes 深拷贝
, and if it is 引用数据类型
, then it is 浅拷贝
.
let z = { a: 3, b: bb , c: { name: ccc } }
let n = { ...z }
n // { a: 3, b: bb , c: { name: ccc } }
n === z // false
n.c === z.c // true
// n.c 跟 z.c 是同一个引用地址
Object Literal Shorthand Syntax
const name = 雪月
// ES5写法
const obj = {
name: name,
f: function () {
console.log(this.name)
},
}
// ES6简写
const obj2 = {
name,
f() {
console.log(this.name)
},
}
obj.f() // 雪月
obj2.f() // 雪月
Do students who use it vue
feel familiar
new Vue({
el: #app ,
data() {
return {
list: [],
}
},
})
includes() for array instances
The Array.prototype.includes method returns a boolean indicating whether an array contains the given value, similar to the string's includes method. ES2016 introduced this method.
;[1, 2, 3].includes(2) // true
;[1, 2, 3].includes(4) // false
;[1, 2, NaN].includes(NaN) // true
Before this method, we usually use the indexOf method of the array to check whether it contains a certain value.
// ES5
if (arr.indexOf(el) !== -1) {
// ...
}
// ES6
if (arr.includes(el)) {
// ...
}
// 那么 indexOf 能不能做到类似于 includes 的写法呢? 我们可以利用 ~ 位运算符
if (~arr.indexOf(el)) {
// ...
}
indexOf
The method has two shortcomings. One is that it is not semantic enough. Its meaning is to find the first occurrence position of the parameter value, so it is not intuitive enough to compare whether it is not equal to -1. The second is that it uses the strict equality operator (===) to judge internally, which will lead to NaN
misjudgments.
;[NaN].indexOf(NaN)
// -1
includes
Using a different judgment algorithm, there is no such problem
;[NaN].includes(NaN)
// true