链式调用?
js中在调用某个非对象上的属性时会报TypeError
的谬误,如下:
let obj = { name: 'aaa', age: 18}console.log(obj.school.address) //Uncaught TypeError: Cannot read property 'address' of undefined
应用链式调用之后,js语句会输入undefined,不会报错
console.log(obj.school?.address) //undefined
空值合并??
为变量 fruit 赋值,如果以后值不存在,则赋为默认值 'apple',能够应用逻辑运算符||
实现,如下:
let value = 0;let fruit = value || 'apple'console.log(fruit) // apple
js假值有false
、null
、0
、""
、undefined
和 NaN
,||
逻辑符会将假值过滤掉,但如果咱们不想要过滤 0
或者 ''
字符,这时能够应用新增合并属性 ??
,合并符只会过滤掉 null
和 undefined
,如下:
fruit = NaN ?? 'apple'console.log(fruit) //NaNfruit = 0 ?? 'apple'console.log(fruit) //0fruit = null ?? 'apple'console.log(fruit) // 'apple'
公有属性
es10 为类class新增了公有属性,公有属性只可能在类外部进行调用,如下:
class Fruit { #shape = 'circle'; constructor(size){ this.size = size; } getShape(){ return this.#shape; }}let apple = new Fruit();console.log(apple.getShape()) // circleconsole.log(apple.#shape) // Uncaught SyntaxError: Private field '#shape' must be declared in an enclosing class
动态字段
类定义之后,类外面的办法是无奈间接拜访的,只能通过定义实例来调用,然而es10新增了 static
字段,通过 static 能够间接调用类办法,如下:
class Fruit { constructor(size){ this.size = size; } getColor(){ return 'red' } static getShape(){ return 'circle'; }}Fruit.getFruit() //circleFruit.getColor() //Uncaught TypeError: Fruit.getColor is not a function
Array.flat(n)
开展嵌套数组的办法,默认开展一层,如果想要开展多层,能够传入参数n,如
let arr = [1,2,[3,[4,5]]]arr.flat() // [1,2,3,[4,5]]arr.flat(2) // [1,2,3,4,5]// Infinity 能够开展所有的嵌套arr.flat(Infinity) // [1,2,3,4,5]
Array.flatMap
flatMap 就是 flat + map 的组合操作:如下
[1,2,3].flatMap(num=>[num, num*num]) // [1, 1, 2, 4, 3, 9]
String.trimStart、String.trimEnd
去除字符前后的空格,同 trimLeft、trimRight
' 123'.trimStart() //'123''123 '.trimStart() //'123'