16 个 JavaScript 简写神技
JavaScript 是一门强大且灵活的语言,拥有丰富的特性和语法糖。分享下 16 个最常用的 JavaScript 的简写技巧,掌握它们可以让我们编写出更简洁、更优雅的代码,并显著提升开发效率(增加摸鱼时间)。
1. 三元运算符简化条件判断
1 2 3 4 5 6 7 8 9 10
| let result; if (someCondition) { result = 'yes'; } else { result = 'no'; }
const result = someCondition ? 'yes' : 'no';
|
2. 空值合并运算符
1 2 3 4 5
| const name = user.name !== null && user.name != undefined ? user.name : 'default';
const name = user.name ?? 'default'
|
3. 可选链操作符
1 2 3 4 5
| const street = user && user.address && user.address.street;
const street = user?.address?.street;
|
4. 数组去重
1 2 3 4 5 6 7
| function unique(arr){ return arr.filter((item, index) => arr.index0f(item) === index); }
const unique = arr => [...new Set(arr)];
|
5. 快速取整
1 2 3 4 5
| const floor = Math.floor(4.9);
const floor = ~~4.9;
|
6. 合并对象
1 2 3 4 5
| const merged = object.assign({}, obj1, obj2);
const merged = {...obj1, ...obj2};
|
7. 短路求值
1 2 3 4 5 6 7
| if (condition) { doSomething(); }
condition && doSomething();
|
8. 默认参数值
1 2 3 4 5 6 7 8
| function greet(name) { name = name || 'Guest'; console.log(`Hello ${name}`); }
const greet = (name = 'Guest') => console.log(`Hello ${name}`);
|
9. 解构赋值
1 2 3 4 5 6
| const first = arr[0]; const second = arr[1];
const [first, second] = arr;
|
10. 字符串转数字
1 2 3 4 5
| const num = parseInt('123');
const num = +'123';
|
11. 多重条件判断
1 2 3 4 5 6 7 8 9
| if (value === 1 || value === 2 || value === 3) { }
if ([1, 2, 3].includes(value)) { }
|
12. 快速幂运算
1 2 3 4 5
| Math.pow(2, 3);
2 ** 3;
|
13. 对象属性简写
1 2 3 4 5
| const obj = { x: x, y: y };
const obj = { x, y };
|
14. 数组映射
1 2 3 4 5 6 7 8 9
| const numbers = [1, 2, 3]; const doubled = numbers.map(function(num) { return num * 2; });
const doubled = numbers.map(num => num * 2);
|
15. 交换变量值
1 2 3 4 5 6 7
| let temp = a; a = b; b = temp;
[a, b] = [b, a];
|
16. 动态对象属性
1 2 3 4 5 6 7 8
| const obj = {}; obj[dynamic + 'name'] = value;
const obj = { [`${dynamic}name`]: value };
|
参考