在 JavaScript 开发中,简洁的代码不仅可读性更高,还能提升开发效率。以下是 12 个实用的 JS 简写技巧,帮助你写出更优雅的代码:
1. 变量声明简写(解构赋值)
传统写法:从对象 / 数组中提取属性时逐个声明
const user = { name: 'Alice', age: 25, city: 'Beijing' };
const name = user.name;
const age = user.age;
const city = user.city;
// 数组同理
const arr = [10, 20, 30];
const a = arr[0];
const b = arr[1];
简写:使用解构赋值一次性提取
const user = { name: 'Alice', age: 25, city: 'Beijing' };
const { name, age, city } = user;
// 数组解构
const arr = [10, 20, 30];
const [a, b] = arr; // 只取前两个元素
2. 三元运算符替代简单 if-else
传统写法:简单条件判断用 if-else
let result;
if (score > 60) {
result = '及格';
} else {
result = '不及格';
}
简写:用三元运算符一行搞定
const result = score > 60 ? '及格' : '不及格';
3. 箭头函数简写
传统写法:普通函数声明
function add(a, b) {
return a + b;
}
// 作为回调函数
const numbers = [1, 2, 3];
numbers.map(function(num) {
return num * 2;
});
简写:箭头函数(单表达式可省略{}和return)
const add = (a, b) => a + b;
// 回调函数简写
const numbers = [1, 2, 3];
numbers.map(num => num * 2);
4. 模板字符串替代字符串拼接
传统写法:用+拼接字符串和变量
const name = 'Bob';
const message = 'Hello, ' + name + '! You have ' + count + ' messages.';
简写:用反引号`和${}拼接
const name = 'Bob';
const message = `Hello, ${name}! You have ${count} messages.`;
5. 函数默认参数
传统写法:在函数内部设置默认值
function greet(name) {
const userName = name || 'Guest'; // 处理未传参的情况
console.log(`Hello, ${userName}`);
}
简写:直接在参数定义时设置默认值
function greet(name = 'Guest') {
console.log(`Hello, ${name}`);
}
// 调用时可省略参数
greet(); // 输出:Hello, Guest
6. 对象属性简写
传统写法:属性名与变量名相同时重复声明
const name = 'Charlie';
const age = 30;
const user = {
name: name,
age: age,
greet: function() { /* ... */ }
};
简写:省略重复的属性名和function关键字
const name = 'Charlie';
const age = 30;
const user = {
name, // 等价于 name: name
age, // 等价于 age: age
greet() { /* ... */ } // 等价于 greet: function(){}
};
7. 扩展运算符简化数组 / 对象操作
传统写法:复制数组或合并数组用concat
// 复制数组
const arr1 = [1, 2, 3];
const arr2 = arr1.concat(); // 复制
// 合并数组
const arr3 = [4, 5];
const merged = arr1.concat(arr3);
简写:用...扩展运算符
// 复制数组
const arr1 = [1, 2, 3];
const arr2 = [...arr1]; // 复制
// 合并数组
const arr3 = [4, 5];
const merged = [...arr1, ...arr3]; // 合并
// 复制对象(浅拷贝)
const obj1 = { a: 1 };
const obj2 = { ...obj1, b: 2 }; // { a:1, b:2 }
8. 短路求值简化条件执行
传统写法:判断条件为真才执行代码
if (isLoggedIn) {
showUserProfile();
}
// 设置默认值
let username;
if (!inputUsername) {
username = 'Anonymous';
}
简写:用&&执行代码,||设置默认值
// 条件为真时执行
isLoggedIn && showUserProfile();
// 设置默认值
const username = inputUsername || 'Anonymous';
9. 可选链操作符?.简化嵌套属性访问
传统写法:访问嵌套对象属性时需层层判断是否存在
const userName = user && user.profile && user.profile.name;
简写:用?.自动处理不存在的属性(避免Cannot read property 'x' of undefined错误)
const userName = user?.profile?.name; // 若中间属性不存在,返回undefined
10. 空值合并运算符??处理默认值
传统写法:用||设置默认值,但会误判0、''等有效值
const score = inputScore || 0; // 若inputScore为0,会被误判为false,返回0(看似正确,但逻辑有问题)
const message = inputMessage || 'No message'; // 若inputMessage为'',会返回'No message'(可能不符合预期)
简写:用??只在值为null或undefined时使用默认值
const score = inputScore ?? 0; // 只有inputScore是null/undefined时才用0
const message = inputMessage ?? 'No message'; // 只有inputMessage是null/undefined时才用默认值
11. 指数运算符简化幂运算
// 传统写法
const squared = Math.pow(3, 3); // 27
// 简写写法
const squared = 3 ** 3; // 27
12. 使用 includes 方法简化条件判断
// 传统写法
if (value === 1 || value === 2 || value === 3) {
// ...
}
// 简写写法
if ([1, 2, 3].includes(value)) {
// ...
}
这些技巧的核心是利用 JavaScript 的语法特性减少冗余代码,同时保持可读性。合理使用它们能显著提升开发效率,但需注意场景(例如复杂逻辑不适合强行简写,以免降低可读性)。