1. 可选链操作符
MDN: 可选链操作符( ?. )允许读取位于连接对象链深处的属性的值,而不必明确验证链中的每个引用是否有效。?. 操作符的功能类似于 . 链式操作符,不同之处在于,在引用为空(nullish ) (null 或者 undefined) 的情况下不会引起错误,该表达式短路返回值是 undefined。与函数调用一起使用时,如果给定的函数不存在,则返回 undefined
例如:
if (res && res.data && res.data.success) {
//code
}
//=>相当于
if (res?.data?.success) {
// code
}
对象
2. 有条件的向对象中添加属性
我们可以使用展开运算符号(...)来有条件地向 JS 对象快速添加属性。
const condition = true;
const person = {
id: 1,
name: 'John Doe',
...(condition && { age: 16 }),
};
// [object Object] {
// age: 16,
// id: 1,
// name: "John Doe"
// }
3. 使用动态键进行对象结构
const person = { id: 1, name: 'judy' };
const { name: personName } = person;
console.log(personName); // 'judy'
Object.entries
大多数开发人员使用 Object.keys 方法来迭代对象。 此方法仅返回对象键的数组,而不返回值。 我们可以使用 Object.entries 来获取键和值
const person = {
name: 'judy',
age: 20
};
Object.keys(person).forEach((key) => {
console.log(`${key} is ${person[key]}`);
});
// 使用 entries 获取键和值
Object.entries(person).forEach(([key, value]) => {
console.log(`${key} is ${value}`);
});
// name is judy
// age is 20
代码优化
空值合并 ?? 操作符
当我们想检查一个变量是否为 null 或 undefined 时,??操作符很有用。当它的左侧操作数为null 或 undefined时,它返回右侧的操作数,否则返回其左侧的操作数。
const empty = 'null' ?? 'hello' //=>hello
const number = 0 || 5; //=> 5
const number = 0 ?? 5;//=> 0
可选链?.
const book = { id:1, title: 'Title', author: null };
// 通常情况下,你会这样做
console.log(book.author.age) // throws error
console.log(book.author && book.author.age); // null
// 使用可选链
console.log(book.author?.age); // undefined
// 或深度可选链
console.log(book.author?.address?.city); // undefined
使用 !! 操作符
const greeting = 'Hello there!';
console.log(!!greeting) // true
const noGreeting = '';
console.log(!!noGreeting); // false
字符串和整数转换
使用 + 操作符将字符串快速转换为数字:
const stringNumer = '123';
console.log(+stringNumer); //123
console.log(typeof +stringNumer); //'number'
要将数字快速转换为字符串,也可以使用 + 操作符,后面跟着一个空字符串:
const myString = 25 + '';
console.log(myString); //'25'
console.log(typeof myString); //'string'
检查数组中的假值
const myArray = [null, false, 'Hello', undefined, 0];
// 过滤虚值
const filtered = myArray.filter(Boolean);
console.log(filtered); // ['Hello']
// 检查至少一个值是否为真
const anyTruthy = myArray.some(Boolean);
console.log(anyTruthy); // true
// 检查所有的值是否为真
const allTruthy = myArray.every(Boolean);
console.log(allTruthy); // false
replaceAll 方法
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
逻辑赋值运算符
注意:??操作符只检查 null 或 undefined 的值。
const a = null;
const b = 3;
a ??= b;
console.log(a); // 3
// 上面等价于
if (a === null || a === undefined) {
a = b;
}
多个条件检查
if (value === 1 || value === 'one' || value === 2 || value === 'two') {
}
//相当于
if ([1, 'one', 2, 'two'].includes(value)) {
}
从数组中移除特定的项
// 删除所有匹配项
function removeItemAll (arr, value) {
let i = 0
while(i < arr.length) {
if (arr[i] === value) {
arr.splice(i, 1)
} else {
++i
}
}
}
const array = [2, 5, 9,5,5]
removeItemAll(array,5)
console.log(array) //[2,9]