0%

第二篇:ES6-ES11的新语法

1.ES6

1.let 和var的区别

作用域不同,var是全局变量而let是根据为位置决定

2.const定义常量,防止变量标识符的重新分配

3.防止对象被改变:Object.freeze(obj)

4.箭头函数代替function关键字:const myFun=(attribute)=>{}

设置默认参数const myFun=(attribute=value)=>{}

5.rest操作符: …args等同于将args数组展开

6.解构赋值:

(1)对象的解构赋值:

1
const user = { name: 'John Doe', age: 34 };
1
const { name, age } = user;//将user的name和age的值赋值给了name和age变量
1
const { name: userName, age: userAge } = user;//将user.name和user.age的值分配给了新变量
1
2
3
4
5
6
const user = {
johnDoe: {
age: 34,
email: 'johnDoe@freeCodeCamp.com'
}
};

嵌套对象的解构赋值:

1
const { johnDoe: { age, email }} = user;//这是解构对象的属性值赋值给具有相同名字的变量:
1
const { johnDoe: { age: userAge, email: userEmail }} = user;//这是将对象的属性值赋值给具有不同名字的变量:

(2)数组的解构赋值:

1
const [a, b] = [1, 2, 3, 4, 5, 6];
1
const [a, b,,, c] = [1, 2, 3, 4, 5, 6];

例:交换变量的值:let a=10; let b=20; [a,b]=[b,a];

1
const [a, b, ...arr] = [1, 2, 3, 4, 5, 7];

arr就是新的数组[3,4,5,7];

(3)模板字面量:

1
2
3
4
5
6
const person = {
name: "Zodiac Hasbro",
age: 56
};
const greeting = `Hello, my name is ${person.name}!
I am ${person.age} years old.`;//占位符${}
1
2
3
4
5
6
const getMousePosition = (x, y) => ({
x: x,
y: y
});//等同于
const getMousePosition = (x, y) => ({ x, y });

1
2
3
4
5
6
const person = {
name: "Taylor",
sayHello: function() {
return `Hello! My name is ${this.name}.`;
}
};
1
2
3
4
5
6
const person = {
name: "Taylor",
sayHello() {
return `Hello! My name is ${this.name}.`;
}
};//简洁的函数声明

构造函数:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
var SpaceShuttle = function(targetPlanet){
this.targetPlanet = targetPlanet;
}
class SpaceShuttle {
constructor(targetPlanet) {
this.targetPlanet = targetPlanet;
}
}
class Book {
constructor(author) {
this._author = author;
}
// getter 定义时的赋值
get writer() {
return this._author;
}
// setter 改变writer属性值的时候
set writer(updatedAuthor) {
this._author = updatedAuthor;
}
}
const novel = new Book('anonymous');
console.log(novel.writer);
novel.writer = 'newAuthor';
console.log(novel.writer);

7.导入模块js文件:

1
<script type="module" src="filename.js"></script>

export导出js的模块:

1
2
3
export const add = (x, y) => {
return x + y;
}
1
2
3
4
5
const add = (x, y) => {
return x + y;
}

export { add };//可以一次导出多个变量或函数

import导入js模块:

1
import { add, subtract } from './math_functions.js'; 

全部导入:

1
import * as myMathModule from "./math_functions.js";

上面的 import 语句会创建一个叫作 myMathModule 的对象。 这只是一个变量名,可以随便命名。 对象包含 math_functions.js 文件里的所有导出,可以像访问对象的属性那样访问里面的函数。 下面是使用导入的 addsubtract 函数的例子:

1
2
myMathModule.add(2,3);
myMathModule.subtract(5,3);

还需要了解另外一种被称为默认导出的 export 的语法。 在文件中只有一个值需要导出的时候,通常会使用这种语法。 它也常常用于给文件或者模块创建返回值。

1
2
3
4
5
6
7
export default function add(x, y) {
return x + y;
}

export default function(x, y) {
return x + y;
}

第一个是命名函数,第二个是匿名函数。

export default 用于为模块或文件声明一个返回值,在每个文件或者模块中应当只默认导出一个值。 此外,你不能将 export defaultvarletconst 同时使用。

还需要一种 import 的语法来导入默认的导出。 在下面的例子里,addmath_functions.js 文件的默认导出。 以下是如何导入它:

1
import add from "./math_functions.js";

这个语法有一处特别的地方, 被导入的 add 值没有被花括号({})所包围。 add 只是一个变量的名字,对应 math_functions.js 文件的任何默认导出值。 在导入默认导出时,可以使用任何名字。

8.Promise:

Promise 是异步编程的一种解决方案 - 它在未来的某时会生成一个值。 任务完成,分执行成功和执行失败两种情况。 Promise 是构造器函数,需要通过 new 关键字来创建。 构造器参数是一个函数,该函数有两个参数 - resolvereject。 通过它们来判断 promise 的执行结果。 用法如下:

1
2
3
const myPromise = new Promise((resolve, reject) => {

});

通过 resolve 和 reject 完成 Promise

Promise 有三个状态:pendingfulfilledrejected。 上一个挑战里创建的 promise 一直阻塞在 pending 状态里,因为没有调用 promise 的完成方法。 Promise 提供的 resolvereject 参数就是用来结束 promise 的。 Promise 成功时调用 resolve,promise 执行失败时调用 reject, 如下文所述,这些方法需要有一个参数。

1
2
3
4
5
6
7
const myPromise = new Promise((resolve, reject) => {
if(condition here) {
resolve("Promise was fulfilled");
} else {
reject("Promise was rejected");
}
});

上面的示例使用字符串作为这些函数的参数,但参数实际上可以是任何格式。 通常,它可能是一个包含数据的对象,你可以将它放在网站或其他地方。

用 then 处理 Promise 完成的情况

当程序需要花费未知的时间才能完成时(比如一些异步操作),一般是服务器请求,promise 很有用。 服务器请求会花费一些时间,当结束时,需要根据服务器的响应执行一些操作。 这可以用 then 方法来实现, 当 promise 完成 resolve 时会触发 then 方法。 例子如下:

1
2
3
myPromise.then(result => {

});//result 即传入 resolve 方法的参数

使用 catch 处理 Promise 失败的情况

当 promise 失败时会调用 catch 方法。 当 promise 的 reject 方法执行时会直接调用。 用法如下:

1
2
3
myPromise.catch(error => {

});//error 是传入 reject 方法的参数。

2.ES7

includes:数组方法,判断是否数组含有某元素,返回布尔值

**:表示幂运算的运算符

1
2
3
const books=["tom","sakura"];
console.log(books.includes("tom"));
console.log(2**10);

async和await:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
//async函数返回值为promise对象
//promise对象的结果由async函数执行的返回值决定
function getData(url) {
return new Promise((resolved, reject) => {
let xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.send();
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300) {
resolved(xhr.response);
} else {
reject(xhr.status);
}
}
};
});
}
async function get(){
let result=getData("http:///localhost:8000");
console.log(result);
}

3.ES8 对象方法的扩展:

1
2
3
4
//Object.keys(obj) 获取对象的键
//Object.values(obj) 获取对象的值
//Object.entries(obj) 获取对象的二维数组形式
//Object.getOwnPropertyDescriptors(obj) 获取对象的描述对象

4.ES9 正则扩展:

1
2
3
4
5
6
7
8
9
10
//命名捕获分组
let str="<a href='http:www.baidu.com'></a>";
const reg=/<a href="(.*)">(.*)<\/a>/;
const result=reg.exec(str);
console.log(result[1]);
const reg1=/<a href="(?<url>.*)">(?<text>.*)<\/a>/;
const result1=reg1.exec(str);
console.log(result.groups.name);
//反向断言 (?<=啊)
//dotAll 新增s修饰符 写在//s

5.ES10:

1
2
3
//Object.fromEntries() 利用传入的二维数组创建一个对象
//flat和flatMap 将数组降维 flat接收数字参数决定降的维度 flatMap将map和flat结合
//Symbol.prototype.description

6.ES11:

1
2
3
4
5
6
7
8
9
//私有属性
class Person{
name;
#age;//私有属性,以#开头
constructor(name,age){
this.name=name;
this.#age=age;
}
}
1
2
//Promise.allSettled([]) 接收数组 每个元素是个Promise对象 始终成功
//Promise.all([]) 接收参数一样 状态取决于参数是否都成功 否则失败
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//String.prototype.matchAll 返回一个可迭代的对象
let str = `
<ul>
<li>
<a>你好</a>
<p>世界</p>
</li>
<li>
<a>Hello World</a>
<p>sakura</p>
</li>
</ul>
`;
const reg = /<li>.*?<a>(.*?)<\/a>.*?<p>(.*?)<\/p>/gs;
const result = str.exec(reg);
for (let v of result) {
console.log(v);
}
1
2
//可选链操作符 ?. 在使用对象的属性之前判断对象是否存在
//动态import import("").then(module=>{module.method()});

BigInt类型:大整形

1
2
3
//大数值的运算
let n=123;
let m=BigInt(n);

globalThis:始终指向全局对象