只有当它使表达式更容易理解时才使用它,而不是盲目的为了简洁而简洁。
1、一行声明变量
你可以将变量声明合并为一行,而不是每个声明使用一行。
let name;
let age;
let favoriteFood = "Pizza";
// Shorthand
let name, age, favoriteFood = "Pizza";
2、空合并
空合并运算符 ?? 如果左侧为空,则返回右侧。否则,它返回左边的值。
let someValue;
if(someValue){
console.log(someValue)
} else {
console.log("Nothing found")
}
// Shorthand
console.log(someValue ?? "Nothing found")
// 输出:
Nothing found
Nothing found
3、可选链
在 JavaScript 中,你可以使用点表示法例如:a.b 去访问对象的属性和方法。
但是,如果你尝试访问未定义对象的属性,你将看到错误。为避免这种情况,你需要确保在访问其属性之前定义该对象:
const a = b && b.somevalue;
// Shorthand
const a = b?.somevalue;
也可以结合空合并运算符给定初始值
cosnt a = b?.somevalue ?? ''
4、将任何值转换为布尔值
在 JavaScript 中,你可以将任何内容转换为布尔值。
要将任何内容转换为布尔值,请使用双感叹号 !!。
!!true // true
!!2 // true
!![] // true
!!"Test" // true
!!false // false
!!0 // false
!!"" // false
5、扩展运算符对数组的相关操作
你可以使用扩展运算符 … 将一个数组的元素扩展到另一个数组中。
例如,让我们使用扩展运算符将两个数字数组合并在一起:
const nums1 = [1, 2, 3];
const nums2 = [4, 5, 6];
let newArray = nums1.concat(nums2);
// Shorthand
newArray = [...nums1, ...nums2];
在向数组添加元素时,你还可以将 .push() 方法替换为扩展运算符。
let numbers = [1, 2, 3];
numbers.push(4);
numbers.push(5);
// Shorthand
numbers = [...numbers, 4, 5];
使用扩展运算符进行解构 你可以使用扩展运算符 … 来解构对象的剩余值。
为了演示,让我们创建一个学生对象。让我们将 name 和 age 属性分配给变量,并将剩余的属性分配给第三个变量:
const student = {
name: "Matt",
age: 23,
city: "Helsinki",
state: "Finland",
};
const name = student.name;
const age = student.age;
const address = { city: student.city, state: student.state };
// Shorthand
const { name, age, ...address } = student;
从数组中删除重复项
你可以通过将数组转换为集合,然后将集合中的值添加回数组来删除数组的重复项。
const nums = [1,1,1,1,3,4,5]
const uniqueNums = [...new Set(nums)];
6、短路评估中的 && 运算符
你是否使用 if 检查来查看表达式的计算结果是否为真?
你可以使用短路 && 运算符对速记进行相同的操作。
var ready = true;
function action(){
console.log("Yeah");
}
if(ready){
action();
}
// Shorthand
ready && action();
7、将值嵌入到字符串中
你可以通过将字符串包装在反引号内并使用 ${} 将变量嵌入到字符串中。
const age = 41;
const sentence = `I'm ${age} years old`;
// result: I'm 41 years old
8、对象属性分配
如果你希望对象键与值具有相同的名称,则可以省略对象文字。
const name = "Luis", city = "Paris", age = 43, food = "Spaghetti";
let person = {
name: name,
city: city,
age: age,
food: food
};
// Shorthand
person = { name, city, age, food };
9、默认值
在 JavaScript 中,你可以拥有一个带有默认参数值的函数。
通过这种方式,你可以在提供或不提供参数值的情况下调用该函数。
function pick(fruit) {
if(fruit === undefined){
console.log("I just picked up a Mango");
} else {
console.log(`I just picked up a ${fruit}`);
}
}
// Shorthand
function pick(fruit="Mango") {
console.log(`I just picked up a ${fruit}`)
}
pick("Pineapple"); // -> I picked up a Pineapple
pick(); // -> I picked up a Mango
10、单线 if-else
在 JavaScript 中,你可以使用三元条件运算符来压缩 if-else 语句。 例如:
const a = 10;
let b;
if (a >= 20) {
b = "big";
} else {
b = "small";
}
// Shorthand
b = a >= 20 ? "big" : "small";
11、对象值作为数组
使用 Object.values() 方法将一个对象的所有值收集到一个数组中。
const info = { name: "Matt", country: "Finland", age: 35 };
let data = [];
for (let key in info) {
data.push(info[key]);
}
// Shorthand
const data = Object.values(info);
12、在数组中查找元素
使用内置的 find() 方法查找与特定条件匹配的元素。
const fruits = [
{ type: "Banana", color: "Yellow" },
{ type: "Apple", color: "Green" }
];
let yellowFruit;
for (let i = 0; i < fruits.length; ++i) {
if (fruits[i].color === "Yellow") {
yellowFruit = fruits[i];
}
}
// Shorthand
yellowFruit = fruits.find((fruit) => fruit.color === "Yellow");
13、检查数组中的项
你可以使用 includes() 方法,而不是使用 indexOf() 方法来检查元素是否在数组中。
let numbers = [1, 2, 3];
const hasNumber1 = numbers.indexOf(1) > -1 // -> True
// Shorthand
const hasNumber1 = numbers.includes(1) // -> True
14、多条件检查
使用 includes() 方法避免条件链。
const num = 1;
if(num == 1 || num == 2 || num == 3){
console.log("Yay");
}
// Shorthand
if([1,2,3].includes(num)){
console.log("Yay");
}
15、用一行代码分配多个值
你可以使用解构在一行代码中分配多个值。
let num1, num2;
num1 = 10;
num2 = 100;
// Shorthand
[num1, num2] = [10, 100];
这也适用于对象:
student = {
name: "Matt",
age: 29,
};
let name = student.name;
let age = student.age;
// Shorthand
let { name, age } = student;
16、在没有第三个变量的情况下交换两个变量
使用解构从数组中提取值。这可以应用于在没有第三个的情况下交换两个变量。
let x = 1;
let y = 2;
let temp = x;
x = y;
y = temp;
// Shorthand
[x, y] = [y, x];
17、 Math.pow() 简写
可以不使用 Math.pow() 函数来将数字求幂,而是使用 ** 运算符作为速记:
Math.pow(4,2); // 16
Math.pow(2,3); // 8
// Shorthand
4**2 // 16
2**3 // 8
18、 Math.floor() 简写
你可以使用 ~~ 运算符作为简写,而不是使用 Math.floor() 函数来向下舍入数字:
Math.floor(5.21) // -> 5.0
// Shorthand
~~5.21 // -> 5.0