1.const 和 let
2.闭包的作用
3.字符串模板
4.解构
数组解构: let [a,b,c] = [1,2,3] // a 1 , b 2 , c 3
let [a,...b] = [1,2,3] // a 1 , b [2,3]
let [x, y , ...z] = [1] // x 1 ,y undefined ,z []
不完全解构:let [a,[b],c] = [1,[2,3],4]. // a1, b2, c 4
对象的解构: let { bar , foo } = { foo :1, bar :3}
变量名和属性名不一致: let { foo :baz } = {foo:1, bar:2} // baz 1
5.数组方法的扩展
find:找出第一个符合条件的成员并返回
let arr = [1,2,3];
//find方法 用于找出第一个符合条件的数组成员,并返回。参数为一个回调函数,所有数组成员依次执行该回调,直到找出第一个返回值为true的成员并返回,如果没有符合条件的成员则返回undefined
arr.find(num=>num===1); // ->1
findIndex
let arr = [1,2,3,4,5]
arr.findIndex((value,index,arr)=>value>3) // ->3
// findIndex方法的用法与find方法非常类似,返回第一个符合条件的数组成员的位置,如果所有成员都不符合条件,则返回-1。
// 与find方法的区别是,此方法返回的是下标,而find方法返回的是元素本身。
array.from
console.log(Array.from('foo'));
// expected output: Array ["f", "o", "o"]
console.log(Array.from([1, 2, 3], x => x + x));
// expected output: Array [2, 4, 6]
// Array.from方法用于将两类对象转为真正的数组:类似数组的对象(array-like object)和可遍历(iterable)的对象(包括 ES6 新增的数据结构 Set 和 Map)。还可以接受第二个参数(一个函数),作用类似于数组的map方法,用来对每个元素进行处理,将处理后的值放入返回的数组。
Array.of
Array.of(12,34,32)//把括号内的参数转换为数组。
// 如果不传参数,返回空数组。
some
let arr = [1,2,3];
arr.some(item=>item>2); // 如果数组内有一个符合结果就返回true,
every
let arr = [1,2,3];
arr.every(item=>item>2); // 如果数组内都符合结果就返回true,
includes
let arr = [1,2,3];
arr.includes(2); // arr.includes方法返回一个布尔值,表示某个数组是否包含给定的值,
//该方法的第二个参数表示搜索的起始位置,默认为0。如果第二个参数为负数,则表示倒数的位置,
//如果这时它大于数组长度(比如第二个参数为-4,但数组长度为3),则会重置为从0开始。
7. 对象的扩展方法 Object.is
Object.is(NaN,NaN) // ->true 返回值为布尔值,判断两个值是否全等
Object.is(undefined,null) // ->false
Object.is(null,null) // ->true
字符串新增方法:
String.fromCodePoint():用于从 Unicode 码点返回对应字符,但是这个方法不能识别码点大于0xFFFF的字符。
String.raw():该方法返回一个斜杠都被转义(即斜杠前面再加一个斜杠)的字符串,往往用于模板字符串的处理方法
startsWith(),:返回布尔值,表示参数字符串是否在原字符串的头部。
endsWith():返回布尔值,表示参数字符串是否在原字符串的尾部。
let s='Hello world!';
s.startsWith('world',6) // true
s.endsWith('Hello',5) // true
s.includes('Hello',6) // false使用第二个参数n时,endsWith的行为与其他两个方法有所不同。它针对前n个字符,而其他两个方法针对从第n个位置直到字符串结束。
实例方法:repeat():方法返回一个新字符串,表示将原字符串重复n次。
'na'.repeat('3') // "nanana"
实例方法:padStart():用于头部补全,padEnd():用于头部补全
'x'.padStart(5,'ab') // 'ababx'
'x'.padStart(4,'ab') // 'abax'
'x'.padEnd(5,'ab') // 'xabab'
'x'.padEnd(4,'ab') // 'xaba'
实例方法:trimStart()消除字符串头部的空格,trimEnd()消除尾部的空格。它们返回的都是新字符串,不会修改原始字符串。
实例方法:replaceAll(),可以一次性替换所有匹配。
实例方法:at()方法接受一个整数作为参数,返回参数指定位置的字符,支持负索引(即倒数的位置)。
数组新增方法:
Number.isFinite()用来检查一个数值是否为有限的(finite),即不是Infinity
Number.isFinite()用来检查一个数值是否为有限的(finite),即不是Infinity
Number.isFinite()用来检查一个数值是否为有限的(finite),即不是Infinity
// ES5的写法
parseInt('12.34') // 12
parseFloat('123.45#') // 123.45
// ES6的写法
Number.parseInt('12.34') // 12
Number.parseFloat('123.45#') // 123.45
Number.isInteger()用来判断一个数值是否为整数。
Number.isInteger(25) // true
Number.isInteger(25.1) // false
Math.trunc方法用于去除一个数的小数部分,返回整数部分。
Math.sign方法用来判断一个数到底是正数、负数、还是零。对于非数值,会先将其转换为数值。
Math.sign(-5) // -1
Math.sign(5) // +1
Math.sign(0) // +0
Math.sign(-0) // -0
Math.sign(NaN) // NaN
Math.cbrt()方法用于计算一个数的立方根。
数组的扩展:
Array.from():方法用于将两类对象转为真正的数组:类似数组的对象(array-like object)和可遍历(iterable)的对象(包括 ES6 新增的数据结构 Set 和 Map)。
下面是一个类似数组的对象,Array.from()将它转为真正的数组。
let arrayLike={'0':'a','1':'b','2':'c',length:3};
// ES5 的写法
var arr1=[].slice.call(arrayLike); // ['a', 'b', 'c']
// ES6 的写法
let arr2=Array.from(arrayLike); // ['a', 'b', 'c']
Array.of():方法用于将一组值,转换为数组。
实例方法:copyWithin():在当前数组内部,将指定位置的成员复制到其他位置(会覆盖原有成员),然后返回当前数组。也就是说,使用这个方法,会修改当前数组。
它接受三个参数。
target(必需):从该位置开始替换数据。如果为负值,表示倒数。
start(可选):从该位置开始读取数据,默认为 0。如果为负值,表示从末尾开始计算。
end(可选):到该位置前停止读取数据,默认等于数组长度。如果为负值,表示从末尾开始计算。
// 将3号位复制到0号位
[1, 2, 3, 4, 5].copyWithin(0, 3, 4)// [4, 2, 3, 4, 5]
// -2相当于3号位,-1相当于4号位
[1, 2, 3, 4, 5].copyWithin(0, -2, -1)// [4, 2, 3, 4, 5]
// 将3号位复制到0号位
[].copyWithin.call({length: 5, 3: 1}, 0, 3)// {0: 1, 3: 1, length: 5}
// 将2号位到数组结束,复制到0号位
let i32a = new Int32Array([1, 2, 3, 4, 5]);i32a.copyWithin(0, 2);// Int32Array [3, 4, 5, 4, 5]
// 对于没有部署 TypedArray 的 copyWithin 方法的平台
// 需要采用下面的写法
[].copyWithin.call(new Int32Array([1, 2, 3, 4, 5]), 0, 3, 4);// Int32Array [4, 2, 3, 4, 5]
find():用于找出第一个符合条件的数组成员, 找出第一个返回值为true的成员,然后返回该成员。如果没有符合条件的成员,则返回undefined
findIndex():返回第一个符合条件的数组成员的位置,如果所有成员都不符合条件,则返回-1。
实例方法:fill():方法使用给定值,填充一个数组。
['a', 'b', 'c'].fill(7)// [7, 7, 7]
new Array(3).fill(7)// [7, 7, 7]
实例方法:entries(),keys() 和 values() 用于遍历数组
唯一的区别是keys()是对键名的遍历、values()是对键值的遍历,entries()是对键值对的遍历。
flat():用于将嵌套的数组“拉平”,变成一维的数组。该方法返回一个新数组,对原数据没有影响,默认拉平一层如果需要多层传整数参数默认为1(如果不管有多少层嵌套,都要转成一维数组,可以用Infinity关键字作为参数。),原数组有空位会跳过
[1, 2, [3, 4]].flat()// [1, 2, 3, 4]
[1, 2, [3, [4, 5]]].flat(2)// [1, 2, 3, 4, 5][1, [2, [3]]].flat(Infinity)// [1, 2, 3]
flatMap():方法对原数组的每个成员执行一个函数,然后对返回值组成的数组执行flat()方法。该方法返回一个新数组,不改变原数组。只能展开一层数组。
// 相当于 [[2, 4], [3, 6], [4, 8]].flat()
[2, 3, 4].flatMap((x) => [x, x * 2]) // [2, 4, 3, 6, 4, 8]
forEach(), filter(), reduce(), every() 和some()都会跳过空位。
map()会跳过空位,但会保留这个值
join()和toString()会将空位视为undefined,而undefined和null会被处理成空字符串。
Array.from()方法会将数组的空位,转为undefined
扩展运算符(...)也会将空位转为undefined。
copyWithin()会连空位一起拷贝。
fill()会将空位视为正常的数组位置。
for...of循环也会遍历空位。
entries()、keys()、values()、find()和findIndex()会将空位处理成undefined。
// 相当于 [[2, 4], [3, 6], [4, 8]].flat()[2,3,4].flatMap((x)=>[x,x*2])// [2, 4, 3, 6, 4, 8]
对象的新增方法
Object.getOwnPropertyDescriptors()
__proto__属性,Object.setPrototypeOf(),Object.getPrototypeOf()
Object.keys(),Object.values(),Object.entries()
Object.fromEntries():Object.fromEntries()方法是Object.entries()的逆操作,用于将一个键值对数组转为对象。
Object.fromEntries([ ['foo', 'bar'], ['baz', 42]])// { foo: "bar", baz: 42 }
Object.fromEntries(new URLSearchParams('foo=bar&baz=qux'))// { foo: "bar", baz: "qux" }
运算符的扩展
2 ** 2 // 4
2 ** 3 // 8
// 相当于 2 ** (3 ** 2)
2**3**2 // 512
//指数运算符可以与等号结合,形成一个新的赋值运算符(**=)。
let a = 1.5;
a **= 2;
// 等同于 a = a * a;
// 之前写法
const firstName=(message&&message.body&&message.body.user&&message.body.user.firstName)||'default';
//现在写法
const firstName = (message?.body?.user?.firstName)||'default';1.短路机制
a?.[++x]// 等同于a == null ? undefined : a[++x]
2.括号的影响
(a?.b).c// 等价于(a == null ? undefined : a.b).c
3.报错场合
// 构造函数new a?.()new a?.b()
// 链判断运算符的右侧有模板字符串a?.`{b}`a?.b`{c}`
// 链判断运算符的左侧是 supersuper?.()super?.foo
// 链运算符用于赋值运算符左侧a?.b = c
4.右侧不得为十进制数值
Null 判断运算符:ES2020 引入了一个新的 Null 判断运算符??。它的行为类似||,但是只有运算符左侧的值为null或undefined时,才会返回右侧的值。
const headerText=response.settings.headerText??'Hello, world!';
const animationDuration=response.settings.animationDuration??300;
//一般结合?.使用
const animationDuration = response.settings?.animationDuration ?? 300;
// 或赋值运算符
x||=y// 等同于x||(x=y)
// 与赋值运算符x&&=y// 等同于x&&(x=y)
// Null 赋值运算符x??=y// 等同于x??(x=y)
Reflect
1.Reflect.get(target, name, receiver): Reflect.get方法查找并返回target对象的name属性,如果没有该属性,则返回undefined。
var myObject = {
foo: 1,
bar: 2,
get baz() {
return this.foo + this.bar;
}
}
Reflect.get(myObject, 'foo') // 1
Reflect.get(myObject, 'bar') // 2
Reflect.get(myObject, 'baz') // 3
2.Reflect.set(target, name, value, receiver):Reflect.set方法设置target对象的name属性等于value。
var myObject = {
foo: 4,
set bar(value) { return this.foo = value; },
};
var myReceiverObject = {
foo: 0,
};
Reflect.set(myObject, 'bar', 1, myReceiverObject);
myObject.foo // 4
myReceiverObject.foo // 1
3.Reflect.has(obj, name):Reflect.has方法对应name in obj里面的in运算符。
var myObject = { foo: 1,};
// 旧写法
'foo' in myObject // true
// 新写法
sReflect.has(myObject, 'foo') // true
4.Reflect.deleteProperty(obj, name):Reflect.deleteProperty方法等同于delete obj[name],用于删除对象的属性。
const myObj = { foo: 'bar' };
delete myObj.foo; // 旧写法
Reflect.deleteProperty(myObj, 'foo'); // 新写法
5.Reflect.construct(target, args):Reflect.construct方法等同于new target(...args),这提供了一种不使用new,来调用构造函数的方法。
function Greeting(name) { this.name = name;}
// new 的写法
const instance = new Greeting('张三');
// Reflect.construct 的写法
const instance = Reflect.construct(Greeting, ['张三']);
6.Reflect.getPrototypeOf(obj):Reflect.getPrototypeOf方法用于读取对象的__proto__属性,对应Object.getPrototypeOf(obj)。
const myObj=newFancyThing();
// 旧写法
Object.getPrototypeOf(myObj)===FancyThing.prototype;
// 新写法
Reflect.getPrototypeOf(myObj)===FancyThing.prototype;
7.Reflect.setPrototypeOf(obj, newProto):方法用于设置目标对象的原型(prototype),对应Object.setPrototypeOf(obj, newProto)方法。它返回一个布尔值,表示是否设置成功。
const myObj={};
// 旧写法
Object.setPrototypeOf(myObj,Array.prototype);
// 新写法
Reflect.setPrototypeOf(myObj,Array.prototype);
myObj.length // 0
8.Reflect.apply(func, thisArg, args):方法等同于Function.prototype.apply.call(func, thisArg, args),用于绑定this对象后执行给定函数。
9.Reflect.defineProperty(target, propertyKey, attributes):方法基本等同于Object.defineProperty,用来为对象定义属性。未来,后者会被逐渐废除,请从现在开始就使用Reflect.defineProperty代替它。
10.Reflect.getOwnPropertyDescriptor(target, propertyKey)
11.Reflect.isExtensible (target)
12.Reflect.isExtensible (target)
13.Reflect.ownKeys (target)
Promise 对象
Promise 的含义:Promise对象代表一个异步操作,有三种状态:pending(进行中)、fulfilled(已成功)和rejected(已失败)
下面是异步加载图片的例子。
functionloadImageAsync(url){
return new Promise(function(resolve,reject){
const image=newImage();image.onload=function(){resolve(image);};image.onerror=function(){reject(newError('Could not load image at '+url));};image.src=url;});}