博客
关于我
20个常用的JavaScript简写技巧
阅读量:490 次
发布时间:2019-03-07

本文共 2035 字,大约阅读时间需要 6 分钟。

20个常用的JavaScript简写技巧

学习JavaScript可以让我们的代码更简洁高效,但有时候仍然有优化空间。以下是20个实用的小技巧,帮助你提升代码质量。

1. 声明变量

在声明多个变量时,可以用逗号分隔。
*长代码:*let x; let y = 20;
*简写方法:*let x, y = 20;

2. 给多个变量赋值

利用数组解构赋值,可以在一行给多个变量赋值。
*长代码:*let a, b, c;
a = 5; b = 8; c = 12;
*简写方法:*let [a, b, c] = [5, 8, 12];

3. 三元运算符

简化条件判断,直接在表达式中使用三元运算符。
长代码:
let marks = 26;
let result;
if (marks >= 30) {
result = 'Pass';
} else {
result = 'Fail';
}
*简写方法:*let result = marks >= 30 ? 'Pass' : 'Fail';

4. 赋默认值

使用 || 短路运算给变量赋默认值。
长代码:
let imagePath;
let path = getImagePath();
if (path !== null && path !== undefined && path !== '') {
imagePath = path;
} else {
imagePath = 'default.jpg';
}
简写方法:
let imagePath = getImagePath() || 'default.jpg';

5. 与(&&&) 短路运算

用于控制流的执行,避免多余操作。
示例:
if (isLoggedIn) {
goToHomepage();
}
简写方法:
isLoggedIn && goToHomepage();

6. 交换两个变量

利用数组解构赋值快速交换两个变量的值。
长代码:
let x = 'Hello', y = 55;
const temp = x;
x = y;
y = temp;
简写方法:[x, y] = [y, x];

7. 箭头函数

简洁地定义函数,适合匿名函数或一行定义。
简写方法:
const add = (num1, num2) => num1 + num2;

8. 模板字符串

用${}符号快速嵌入变量,简化字符串拼接。
示例:
console.log('You got a missed call from ${number} at ${time}');

9. 多行字符串

利用模板字符串一行化处理多行文本。
简写方法:
console.log(...${step}...);

10. 多条件检查

将可能的值放入数组,使用includes()或indexOf()判断是否存在。

示例:

if([1, 'one', 2, 'two'].includes(value)) {
// 执行代码
}

11. 对象属性复制

直接在对象语句中使用属性名,节省赋值代码。
示例:
let obj = {
firstname: 'Amitav',
lastname: 'Mishra'
};

12. 字符串转数字

使用+运算符快速转换字符串为数字。
简写方法:
let total = +'453';

13. 重复字符串

利用repeat()方法快速生成重复字符串。
示例:
'Hello '.repeat(5);
'sorry\n'.repeat(100);

14. 指数幂

直接使用运算符计算幂,简化代码。
简写方法:
4
3 = 64;

15. 双非位运算符

替代Math.floor(),快速将浮点数取整。
简写方法:
~~6.8 = 6;

16. 找最大和最小数字

用扩展符...传递数组,直接调用Math.max()和Math.min()。
示例:
Math.max(...[2,8,15,4]); // 15
Math.min(...[2,8,15,4]); // 2

17. For循环

以数组对象为基础,简写for循环逻辑。
示例:
const arr = [10,20,30,40];
for (const val of arr) {
console.log(val);
}

18. 合并数组

使用扩展符...快速合并多个数组或列表。
简写方法:
const arr2 = [...arr1, 60,80];

19. 深拷贝对象

利用JSON.stringify和parse,进行深度复制。
简写方法:
const cloneObj = JSON.parse(JSON.stringify(obj));

20. 取字符串字符

直接索引字符串获取特定位置的字符。
简写方法:
str[2];

这些小技巧可以帮助你在代码中更高效地表达想法,提升开发体验。

转载地址:http://tjncz.baihongyu.com/

你可能感兴趣的文章
Nmap端口扫描工具Windows安装和命令大全(非常详细)零基础入门到精通,收藏这篇就够了
查看>>
NMAP网络扫描工具的安装与使用
查看>>
NMF(非负矩阵分解)
查看>>
nmon_x86_64_centos7工具如何使用
查看>>
NN&DL4.1 Deep L-layer neural network简介
查看>>
NN&DL4.3 Getting your matrix dimensions right
查看>>
NN&DL4.7 Parameters vs Hyperparameters
查看>>
NN&DL4.8 What does this have to do with the brain?
查看>>
nnU-Net 终极指南
查看>>
No 'Access-Control-Allow-Origin' header is present on the requested resource.
查看>>
No 'Access-Control-Allow-Origin' header is present on the requested resource.
查看>>
NO 157 去掉禅道访问地址中的zentao
查看>>
no available service ‘default‘ found, please make sure registry config corre seata
查看>>
No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?
查看>>
no connection could be made because the target machine actively refused it.问题解决
查看>>
No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
查看>>
No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
查看>>
No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
查看>>
No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
查看>>
No mapping found for HTTP request with URI [/logout.do] in DispatcherServlet with name 'springmvc'
查看>>