1.使用?. (ES2020)条件式访问属性
例如 book.contents?.ch01?.sect1 => undefined: book.contents没有ch01这个属性
// 取得surname、null 或 undefined 的简介技术
let surname= book & book.author && book.author.surname
let surname = book?.author?.surname
2.解读一个面向对象
class Point {
constructor(x,y) { //构造函数,用于初始化新实例,
this.x = x; // 默认创建 2个对象属性,x,y
this.y = y;
}
distance() {
return Math.sqrt(this.x * this.x + this.y * this.y)
}
}
//使用Point()构造函数和 new创建Point对象
let p = new Point(1,1)
3.javascript提供的api->运用到字符串
比如 substring,slice,split indexOf,lastIndexOf,replace,toLowerCase toUpperCase,charAt,trim
es6之后增加的,比如startsWith,endsWith,includes,normalize.,padStart,padEnd,concat,trimStart,trimEdn
记住,字符串是不可以修改的,像replace()和toUpperCase()这样的方法都是返回新字符串。
4.es6可以使用Array.form()复制数值
5.es6 给函数定义默认参数
function copy(p=5) { //参数p 在没有值得情况下,默认值是5
return p * 2
}
6.先定义(??) ES2020操作符
先定义(??),求值其先定义的操作数,如果其左操作数不是null 或者undefined,就返回该值,否则,它会返回右操作值。
表达式 a ?? b等价于
(a !== null && a !== undefined) ? a : b
很有用,当你的值是0,空字符串,false,你又想要的时候,就可以这么写
let max = maxWidth ?? 500;
如果此时maxWidth传值是0,就是可以正常赋值了。