1. 有条件地添加对象添加属性
const condition = true;
const person = {
id: 1,
name: 'John Doe',
...(condition && { age: 16 })
}
要点:&&都为true返回第最后一个求值表达式,...扩展成person对象的一部分。
2. 检查属性是否存在对象中
用in检查js对象中是否存在某个值
const person = { name: 'a', sa: 1111 }
console.log( name in person ) // true
3. 空值合并??操作符
可以用??来检查变量是否为null或undefined,当变量是其中一个,则返回右侧操作数,不是返回变量
const foo = null ?? 'hello' // hello
4. 可选链?.
我们是不是经常遇到这样的错误: TypeError: Cannot read property ‘foo’ of null。这对每一个毅开发人员来说都是一个烦人的问题。引入可选链就是为了解决这个问题。一起来看看:
console.log(book.author && book.author.age) => console.log(book.author?.age)
console.log(person.printName()) => console.log(person.aaa?.()) //函数形式
5. 使用!!操作符
!!运算符可用于将表达式的结果快速转换成布尔值
const a = '111'
console.log(!!a) // true
6. 字符串和整数转换
使用+操作符将字符串快速转换为数字:
const stringNumer = '123';console.log(+stringNumer); //123console.log(typeof +stringNumer); //'number'复制代码
要将数字快速转换为字符串,也可以使用+操作符,后面跟着一个空字符串:
const myString = 25 + '';console.log(myString); //'25'console.log(typeof myString); //'string'复制代码
这些类型转换非常方便,但它们的清晰度和代码可读性较差。所以实际开发,需要慎重的选择使用。
7. replaceAll 方法
在 JS 中,要将所有出现的字符串替换为另一个字符串,我们需要使用如下所示的正则表达式:
const str = 'Red-Green-Blue';// 只规制第一次出现的str.replace('-', ' '); // Red Green-Blue// 使用 RegEx 替换所有匹配项str.replace(/\-/g, ' '); // Red Green Blue复制代码
但是在 ES12 中,一个名为replaceAll的新方法被添加到String.prototype中,它用另一个字符串值替换所有出现的字符串。
str.replaceAll('-', ' '); // Red Green Blue
网友评论