让我们来看 40 个 JavaScript 简写技巧,每个都附带未简写的对比代码:
1. 变量声明和赋值
// 未简写
let x = 1;
let y = 2;
let z = 3;
// 简写
let [x, y, z] = [1, 2, 3];
2. 多个条件判断
// 未简写
if (value === 1 || value === 2 || value === 3) {
// ...
}
// 简写
if ([1, 2, 3].includes(value)) {
// ...
}
3. 对象属性赋值
// 未简写
const name = 'Tom';
const age = 20;
const user = {
name: name,
age: age
};
// 简写
const user = { name, age };
4. 空值检查
// 未简写
const value = someValue !== null && someValue !== undefined ? someValue : defaultValue;
// 简写
const value = someValue ?? defaultValue;
5. 对象方法定义
// 未简写
const obj = {
sayHello: function() {
console.log('Hello');
}
};
// 简写
const obj = {
sayHello() {
console.log('Hello');
}
};
6. 字符串模板
// 未简写
const message = 'Hello ' + name + ', you are ' + age + ' years old';
// 简写
const message = `Hello ${name}, you are ${age} years old`;
7. 数组展开
// 未简写
const combined = array1.concat(array2);
// 简写
const combined = [...array1, ...array2];
8. 对象展开
// 未简写
const merged = Object.assign({}, obj1, obj2);
// 简写
const merged = { ...obj1, ...obj2 };
9. 可选链操作
// 未简写
const street = user && user.address && user.address.street;
// 简写
const street = user?.address?.street;
10. 数字转换
// 未简写
const num = parseInt('123');
// 简写
const num = +'123';
11. 布尔值转换
// 未简写
const bool = Boolean(value);
// 简写
const bool = !!value;
12. 数组去重
// 未简写
function unique(arr) {
return arr.filter((item, index) => arr.indexOf(item) === index);
}
// 简写
const unique = arr => [...new Set(arr)];
13. 条件执行
// 未简写
if (condition) {
doSomething();
}
// 简写
condition && doSomething();
14. 默认参数
// 未简写
function greet(name) {
name = name || 'Guest';
return `Hello ${name}`;
}
// 简写
const greet = (name = 'Guest') => `Hello ${name}`;
15. 对象属性动态命名
// 未简写
const obj = {};
obj[dynamicKey] = value;
// 简写
const obj = {
[dynamicKey]: value
};
16. 数组映射
// 未简写
const numbers = [1, 2, 3];
const doubled = numbers.map(function(num) {
return num * 2;
});
// 简写
const doubled = numbers.map(num => num * 2);
17. 数组过滤
// 未简写
const filtered = numbers.filter(function(num) {
return num > 5;
});
// 简写
const filtered = numbers.filter(num => num > 5);
18. 数组查找
// 未简写
const found = numbers.find(function(num) {
return num === 5;
});
// 简写
const found = numbers.find(num => num === 5);
19. 对象解构赋值
// 未简写
const firstName = user.firstName;
const lastName = user.lastName;
// 简写
const { firstName, lastName } = user;
20. 数组解构赋值
// 未简写
const first = array[0];
const second = array[1];
// 简写
const [first, second] = array;
21. 函数返回对象
// 未简写
function createUser(name, age) {
return {
name: name,
age: age
};
}
// 简写
const createUser = (name, age) => ({ name, age });
22. 多重条件检查
// 未简写
if (value === 1 || value === 2 || value === 3) {
// ...
}
// 简写
if ([1, 2, 3].includes(value)) {
// ...
}
23. 字符串重复
// 未简写
let str = '';
for (let i = 0; i < 5; i++) {
str += 'a';
}
// 简写
const str = 'a'.repeat(5);
24. 数组填充
// 未简写
const array = [];
for (let i = 0; i < 5; i++) {
array.push(0);
}
// 简写
const array = Array(5).fill(0);
25. 对象值检查
// 未简写
const hasValue = Object.keys(obj).length > 0;
// 简写
const hasValue = !!Object.keys(obj).length;
好的,让我们继续看剩下的简写技巧(26-40):
26. 交换变量值
// 未简写
let temp = a;
a = b;
b = temp;
// 简写
[a, b] = [b, a];
27. 指数运算
// 未简写
const power = Math.pow(2, 3);
// 简写
const power = 2 ** 3;
28. 数字取整
// 未简写
const int = Math.floor(3.14);
// 简写
const int = ~~3.14;
// 或者
const int = 3.14 | 0;
29. 条件对象属性
// 未简写
const obj = {
name: 'Tom'
};
if (condition) {
obj.age = 25;
}
// 简写
const obj = {
name: 'Tom',
...(condition && { age: 25 })
};
30. 数组最大/最小值
// 未简写
const max = Math.max.apply(null, array);
const min = Math.min.apply(null, array);
// 简写
const max = Math.max(...array);
const min = Math.min(...array);
31. 对象属性存在检查
// 未简写
const hasProperty = object.property !== undefined;
// 简写
const hasProperty = 'property' in object;
32. 多重赋值
// 未简写
x = 1;
y = 1;
z = 1;
// 简写
x = y = z = 1;
33. 数组转对象
// 未简写
const obj = {};
array.forEach(item => obj[item.id] = item);
// 简写
const obj = Object.fromEntries(array.map(item => [item.id, item]));
34. 字符串首字母大写
// 未简写
const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1);
// 简写
const capitalize = str => `${str[0].toUpperCase()}${str.slice(1)}`;
35. 条件赋值
// 未简写
let value;
if (condition) {
value = 'yes';
} else {
value = 'no';
}
// 简写
const value = condition && 'yes' || 'no';
36. 数组扁平化
// 未简写
function flatten(arr) {
return arr.reduce((flat, toFlatten) => {
return flat.concat(Array.isArray(toFlatten) ? flatten(toFlatten) : toFlatten);
}, []);
}
// 简写
const flatten = arr => arr.flat(Infinity);
37. 移除数组假值
// 未简写
const compact = arr => arr.filter(item => Boolean(item));
// 简写
const compact = arr => arr.filter(Boolean);
38. 随机数生成
// 未简写
const random = Math.floor(Math.random() * (max - min + 1)) + min;
// 简写
const random = (min, max) => ~~(Math.random() * (max - min + 1)) + min;
39. 对象值转数组
// 未简写
const values = Object.keys(obj).map(key => obj[key]);
// 简写
const values = Object.values(obj);
40. 检查对象是否为空
// 未简写
const isEmpty = obj => {
for (let prop in obj) {
if (obj.hasOwnProperty(prop)) return false;
}
return true;
}
// 简写
const isEmpty = obj => Object.keys(obj).length === 0;
注意事项:
- 并非所有简写都适合所有场景,要根据具体情况选择
- 代码可读性比简写更重要
- 团队开发中要遵循统一的代码规范
- 某些简写可能会影响性能,使用时要权衡
- 确保简写代码的兼容性和浏览器支持情况