Home > Web Front-end > Front-end Q&A > What are the new operators in es6?

What are the new operators in es6?

青灯夜游
Release: 2023-01-18 18:36:26
Original
1271 people have browsed it

es6 new operators include: 1. Optional chain operator "?.", which can determine whether the properties before the operator are valid, thereby reading the properties of the object in a chain or returning undefined; 2. Exponential operation Operator "**", infix operator used for exponential operations, syntax "x ** y"; 3. Null value merging operator "??"; 4. Logical assignment operators "&&=", "|| =", "??=", mainly perform logical operations on itself, and then assign the subsequent value to it; 5. Extension operator "...".

What are the new operators in es6?

The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.

Question


Interviewer: Can you tell us about the new operators in es6?

Interviewer: Um. . .

Interviewer: For example, optional chaining operator?

Interviewer: Um. . .

Interviewer: Okay, that’s it for today’s interview.

Interviewer: Um. . .

The above scenes are purely fictitious and may be similar, hahaha?.

Today, let’s learn several new operators in es6 and consolidate them.

Operator

Optional Chain Operator

A property of an object. If this property is an object, it also There are sub-properties. When accessing this sub-property, such as

var obj = {a: {key: 'val'}}
console.log(obj.a.key) // val
Copy after login

, if the property does not exist, an error may be reported.

var obj = {key: 'val'}
console.log(obj.a.key) // error: Cannot read properties of undefined (reading 'key')
Copy after login

If you want to be compatible with this situation, you need to add a default value to be compatible

var obj = {key: 'val'}
console.log((obj.a || {}).key) // undefined
Copy after login

If the level is too deep, it will be difficult to read.

(((obj.a || {}).b || {}).c || {}).d

// 或者
obj.a && obj.a.b && obj.a.b.c && obj.a.b.c.d
Copy after login

The optional chain operator is used to improve this writing method. It is represented by ?..

The above example can be rewritten using the optional chain operator

obj.a?.key
obj.a?.b?.c?.d
Copy after login

The effect is the same. Does it increase readability and save code?

If it is found that there is no such attribute, subsequent point operations will not be performed.

It can also be written when the function is executed. Compatible with cases where the function may not be a function. In this case, the function name needs to be defined first or have a value, otherwise an error will still be reported.

var fn
fn?.() // 不会报错

fn1?.() // 报错
Copy after login

Optional chaining cannot be used on the super keyword, template strings, instantiation constructors, the left side of assignment operators, etc.

super?.fn() // error

new Fn?.a() // error

obj.a?.`${b}` // error

obj?.a = obj
Copy after login

Exponent operator

We used to calculate powers like this

Math.pow(2,3) // 8
Copy after login

Now we can calculate it through the exponent operator, use** means

2 ** 3 // 8
Copy after login

can also be written consecutively

2** 3 ** 3 // 134217728
Copy after login

. Maybe you are wondering why it is so big, because it is calculated from the right. Equivalent to 2**(3 ** 3).

Null value merging operator (also called Null judgment operator)

This operator is represented by ??. The default value will only be executed when the value on the left is undefined or null.

Let’s take a look at an example:

var a = '' ?? 'default'
console.log(a) // ''

var a = 0 ?? 'default'
console.log(a) // 0

var a = 123 ?? 'default'
console.log(a) // 123

var a = undefined ?? 'default'
console.log(a) // default

var a = undefined ?? 'default'
console.log(a) // default
Copy after login

If mixed with && or ||, you need to add ()Display the priority, otherwise an error will be reported.

var a = undefined ?? 'default' && 'a' // error
Copy after login

Logical assignment operator

There are three logical assignment operators:

  • Logical union assignment operator (&&=)
  • Logical or assignment operator (||=)
  • Null value merge assignment operator (??=)

Mainly performs logical operations on itself, and then Assign the following value to it.

Let’s take a look at it through an example:

var a,b,c

a &&= 1 // undefined
//等同于
a && (a = 1)

b ||= 1 // 1
//等同于
b || (b = 1)

c ??= 1 // 1
//等同于
c ?? (c = 1)
Copy after login

Expand operator …

Expand operator … was introduced in ES6 to expand the iterable object into its separate elements , the so-called iterable object is any object that can be traversed using a for of loop, such as: array, string, Map, Set, DOM node, etc.

1. Copy array objects

Using the expansion operator to copy an array is a common operation in ES6:

const years = [2018, 2019, 2020, 2021];
const copyYears = [...years];

console.log(copyYears); // [ 2018, 2019, 2020, 2021 ]
Copy after login

The expansion operator copies an array, onlyThe first layer is deep copy, that is, using the spread operator to copy a one-dimensional array is a deep copy. See the following code:

const miniCalendar = [2021, [1, 2, 3, 4, 5, 6, 7], 1];

const copyArray = [...miniCalendar];
console.log(copyArray); // [ 2021, [ 1, 2, 3, 4, 5, 6, 7 ], 1 ]

copyArray[1][0] = 0;
copyArray[1].push(8);
copyArray[2] = 2;
console.log(copyArray); // [ 2021, [ 0, 2, 3, 4, 5, 6, 7, 8 ], 2 ]
console.log(miniCalendar); // [ 2021, [ 0, 2, 3, 4, 5, 6, 7, 8 ], 1 ]
Copy after login

Put the printed results together to make it clearer. The comparison is as follows:

1. Reassign the first element of the second element of the array to 0; 2. Add an element 8 to the second element of the array; 3. Reassign the third element of the array to 2From the results, the second element of the array is an array, which is larger than 1 dimension. Changes to the elements inside will cause the original variable to The value changes accordingly

拷贝对象,代码如下:

const time = {
    year: 2021,
    month: 7,
    day: {
        value: 1,
    },
};
const copyTime = { ...time };
console.log(copyTime); // { year: 2021, month: 7, day: { value: 1 } }
Copy after login

扩展运算符拷贝对象只会在一层进行深拷贝,从下面代码是基于上面代码:

copyTime.day.value = 2;
copyTime.month = 6;
console.log(copyTime); // { year: 2021, month: 6, day: { value: 2 } }
console.log(time); // { year: 2021, month: 7, day: { value: 2 } }
Copy after login

从打印的结果看,扩展运算符只对对象第一层进行了深拷贝。

严格来讲,扩展运算符不执行深拷贝

2. 合并操作

先来看数组的合并,如下:

const halfMonths1 = [1, 2, 3, 4, 5, 6];
const halfMonths2 = [7, 8, 9, 10, 11, 12];

const allMonths = [...halfMonths1, ...halfMonths2];
console.log(allMonths); // [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ]
Copy after login

合并对象,在合并对象时,如果一个键已经存在,它会被具有相同键的最后一个对象给替换。

const time1 = {
    month: 7,
    day: {
        value: 1,
    },
};
const time2 = {
    year: 2021,
    month: 8,
    day: {
        value: 10,
    },
};
const time = { ...time1, ...time2 };
console.log(time); // { month: 8, day: { value: 10 }, year: 2021 }
Copy after login

3. 参数传递

const sum = (num1, num2) => num1 + num2;

console.log(sum(...[6, 7])); // 13
console.log(sum(...[6, 7, 8])); // 13
Copy after login

从上面的代码看,函数定义了多少个参数,扩展运算符传入的值就是多少个。

math 函数一起使用,如下:

const arrayNumbers = [1, 5, 9, 3, 5, 7, 10];
const min = Math.min(...arrayNumbers);
const max = Math.max(...arrayNumbers);
console.log(min); // 1
console.log(max); // 10
Copy after login

4. 数组去重

Set 一起使用消除数组的重复项,如下:

const arrayNumbers = [1, 5, 9, 3, 5, 7, 10, 4, 5, 2, 5];
const newNumbers = [...new Set(arrayNumbers)];
console.log(newNumbers); // [ 1,  5, 9, 3, 7, 10, 4, 2 ]
Copy after login

5. 字符串转字符数组

String 也是一个可迭代对象,所以也可以使用扩展运算符 ... 将其转为字符数组,如下:

const title = "china";
const charts = [...title];
console.log(charts); // [ 'c', 'h', 'i', 'n', 'a' ]
Copy after login

进而可以简单进行字符串截取,如下:

const title = "china";
const short = [...title];
short.length = 2;
console.log(short.join("")); // ch
Copy after login

6. NodeList 转数组

NodeList 对象是节点的集合,通常是由属性,如 Node.childNodes 和方法,如 document.querySelectorAll 返回的。

NodeList 类似于数组,但不是数组,没有 Array 的所有方法,例如findmapfilter 等,但是可以使用 forEach() 来迭代。

可以通过扩展运算符将其转为数组,如下:

const nodeList = document.querySelectorAll(".row");
const nodeArray = [...nodeList];
console.log(nodeList);
console.log(nodeArray);
Copy after login

What are the new operators in es6?

7. 解构变量

解构数组,如下:

const [currentMonth, ...others] = [7, 8, 9, 10, 11, 12];
console.log(currentMonth); // 7
console.log(others); // [ 8, 9, 10, 11, 12 ]
Copy after login

解构对象,如下:

const userInfo = { name: "Crayon", province: "Guangdong", city: "Shenzhen" };
const { name, ...location } = userInfo;
console.log(name); // Crayon
console.log(location); // { province: 'Guangdong', city: 'Shenzhen' }
Copy after login

8. 打印日志

在打印可迭代对象的时候,需要打印每一项可以使用扩展符,如下:

const years = [2018, 2019, 2020, 2021];
console.log(...years); // 2018 2019 2020 2021
Copy after login

【相关推荐:javascript学习教程

The above is the detailed content of What are the new operators in es6?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
Variable descriptionResultOperation
copyArray[ 2021, [ 1, 2, 3, 4, 5, 6, 7 ], 1 ] Copy ArrayminiCalendar
##copyArray[ 2021, [ 0, 2, 3, 4, 5, 6, 7, 8 ], 2 ]
miniCalendar[ 2021, [ 0, 2, 3, 4, 5, 6, 7, 8 ], 1 ]