20 个简洁的 JS 代码片段
逆锋起笔
共 8163字,需浏览 17分钟
·
2021-09-03 12:29
1、单行 If-Else 语句
const age = 12;
let ageGroup;
// LONG FORM
if (age > 18) {
ageGroup = "An adult";
} else {
ageGroup = "A child";
}
// SHORTHAND
ageGroup = age > 18 ? "An adult" : "A child";
2、从数组中删除重复项
const numbers = [1, 1, 20, 3, 3, 3, 9, 9];
const uniqueNumbers = [...new Set(numbers)]; // -> [1, 20, 3, 9]
3、 较短的 If-Else 的空合并
let maybeSomething;
// LONG FORM
if(maybeSomething){
console.log(maybeSomething)
} else {
console.log("Nothing found")
}
//SHORTHAND
console.log(maybeSomething ?? "Nothing found")
4、防止崩溃的可选链
const student = {
name: "Matt",
age: 27,
address: {
state: "New York"
},
};
// LONG FORM
console.log(student && student.address && student.address.ZIPCode); // Doesn't exist - Returns undefined
// SHORTHAND
console.log(student?.address?.ZIPCode); // Doesn't exist - Returns undefined
5、在没有第三个变量的情况下交换两个变量
let x = 1;
let y = 2;
// LONGER FORM
let temp = x;
x = y;
y = temp;
// SHORTHAND
[x, y] = [y, x];
6、将任何值转换为布尔值
!!true // true
!!2 // true
!![] // true
!!"Test" // true
!!false // false
!!0 // false
!!"" // false
7、扩展运算符
const nums1 = [1, 2, 3];
const nums2 = [4, 5, 6];
// LONG FORM
let newArray = nums1.concat(nums2);
// SHORTHAND
newArray = [...nums1, ...nums2];
let numbers = [1, 2, 3];
// LONGER FORM
numbers.push(4);
numbers.push(5);
// SHORTHAND
numbers = [...numbers, 4, 5];
8、传播解构
const student = {
name: "Matt",
age: 23,
city: "Helsinki",
state: "Finland",
};
// LONGER FORM
const name = student.name;
const age = student.age;
const address = { city: student.city, state: student.state };
// SHORTHAND
const { name, age, ...address } = student;
9、 使用 && 进行短路评估
var isReady = true;
function doSomething(){
console.log("Yay!");
}
// LONGER FORM
if(isReady){
doSomething();
}
// SHORTHAND
isReady && doSomething();
10、类固醇的字符串
const age = 41;
const sentence = `I'm ${age} years old`;
// result: I'm 41 years old
11、 从数组中查找特定元素
const fruits = [
{ type: "Banana", color: "Yellow" },
{ type: "Apple", color: "Green" }
];
// LONGER FORM
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");
12、对象属性赋值
const name = "Luis", city = "Paris", age = 43, favoriteFood = "Spaghetti";
// LONGER FORM
const person = {
name: name,
city: city,
age: age,
favoriteFood: favoriteFood
};
// SHORTHAND
const person = { name, city, age, favoriteFood };
13、压缩 For 循环
const numbers = [1, 2, 3, 4, 5];
// LONGER FORM
for(let i = 0; i < numbers.length; i++){
console.log(numbers[i]);
}
// SHORTHAND
numbers.forEach(number => console.log(number));
14、 默认功能参数
// LONG FORM
function pickUp(fruit) {
if(fruit === undefined){
console.log("I picked up a Banana");
} else {
console.log(`I picked up a ${fruit}`);
}
}
// SHORTHAND
function pickUp(fruit = "Banana") {
console.log(`I picked up a ${fruit}`)
}
pickUp("Mango"); // -> I picked up a Mango
pickUp(); // -> I picked up a Banana
15、将对象的值收集到数组中
const info = { name: "Matt", country: "Finland", age: 35 };
// LONGER FORM
let data = [];
for (let key in info) {
data.push(info[key]);
}
// SHORTHAND
const data = Object.values(info);
16、检查一个项目是否存在于数组中
let numbers = [1, 2, 3];
// LONGER FORM
const hasNumber1 = numbers.indexOf(1) > -1 // -> True
// SHORTHAND/CLEANER APPROACH
const hasNumber1 = numbers.includes(1) // -> True
17、压缩多个条件
const num = 1;
// LONGER FORM
if(num == 1 || num == 2 || num == 3){
console.log("Yay");
}
// SHORTHAND
if([1,2,3].includes(num)){
console.log("Yay");
}
18、 指数运算符
// LONGER FORM
Math.pow(4,2); // 16
Math.pow(2,3); // 8
// SHORTHAND
4**2 // 16
2**3 // 8
19、 Math.floor() 简写
// LONG FORM
Math.floor(5.25) // -> 5.0
// SHORTHAND
~~5.25 // -> 5.0
20、 用一行代码分配多个值
let num1, num2;
// LONGER FORM
num1 = 10;
num2 = 100;
// SHORTHAND
[num1, num2] = [10, 100];
student = {
name: "Matt",
age: 29,
};
// LONGER FORM
let name = student.name;
let age = student.age;
// SHORTHAND
let { name, age } = student;
逆锋起笔
是一个专注于程序员圈子的技术平台,你可以收获最新技术动态
、最新内测资格
、BAT等大厂大佬的经验
、增长自身
、学习资料
、职业路线
、赚钱思维
,微信搜索逆锋起笔
关注!
评论