我们经常会写一些 JavaScript 代码,但是如何写出干净又易维护的代码呢?本文将讲解 17 个 JavaScript 代码的技术帮助你提高编程水平,此外,本文可以帮助您为 2021 年的 JavaScript 面试做好准备。

(注意,我会把差的代码放在上面用 //longhand  注释的,好的代码放在下面用 //shorthand  注释的,以作比较)

1. If 多个条件的时候

有时候你会经常判断一个变量是否等于多个值的情况:

//longhand
if (x === 'abc' || x === 'def' || x === 'ghi' || x ==='jkl') {
//logic
} //shorthand
if (['abc', 'def', 'ghi', 'jkl'].includes(x)) {
//logic
}

2. If true … else

if else? 还不如用三元运算符

// Longhand
let test: boolean;
if (x > 100) {
test = true;
} else {
test = false;
} // Shorthand
let test = (x > 10) ? true : false;
//or we can simply use
let test = x > 10;
console.log(test);

三元运算符还可以嵌套,像下面这样:

let x = 300,
let test2 = (x > 100) ? 'greater 100' : (x < 50) ? 'less 50' : 'between 50 and 100';
console.log(test2); // "greater than 100"

但是不建议嵌套太多层的。

3. Null, Undefined, 空检查

前面有空值,如何判断?

// Longhand
if (first !== null || first !== undefined || first !== '') {
let second = first;
} // Shorthand
let second = first|| '';

4. Null Value 检查与分配默认值

let first = null,
let second = first || '';
console.log("null check", test2); // output will be ""

5. Undefined 检查与分配默认值

let first= undefined,
let second = first || '';
console.log("undefined check", test2); // output will be ""

6.foreach 循环

如何更好的迭代?

// Longhand
for (var i = 0; i < testData.length; i++) // Shorthand
for (let i in testData) 或 for (let i of testData)

上面 let i inlet i of 是比较好的方式,

或者下面这样:使用 forEach

function testData(element, index, array) {
console.log('test[' + index + '] = ' + element);
} [11, 24, 32].forEach(testData);
// prints: test[0] = 11, test[1] = 24, test[2] = 32

7. 比较返回

在 return 语句中使用比较将避免我们的 5 行代码,并将它们减少到 1 行。

// Longhand
let test;
function checkReturn() {
if (!(test === undefined)) {
return test;
} else {
return callMe('test');
}
}
var data = checkReturn();
console.log(data); //output test
function callMe(val) {
console.log(val);
} // Shorthand
function checkReturn() {
return test || callMe('test');
}

8. 函数调用简单的方式

用三元运算符解决函数调用

// Longhand
function test1() {
console.log('test1');
};
function test2() {
console.log('test2');
};
var test3 = 1;
if (test3 == 1) {
test1();
} else {
test2();
} // Shorthand
(test3 === 1? test1:test2)();

9. Switch

switch 有时候太长?看看能不能优化

// Longhand
switch (data) {
case 1:
test1();
break; case 2:
test2();
break; case 3:
test();
break;
// And so on...
} // Shorthand
var data = {
1: test1,
2: test2,
3: test
}; data[anything] && data[anything]();

10. 多行字符串速记

字符串多行时,如何更好的处理?用 +  号?

//longhand
const data = 'abc abc abc abc abc abc\n\t'
+ 'test test,test test test test\n\t' //shorthand
const data = `abc abc abc abc abc abc
test test,test test test test`

11.Implicit Return Shorthand

当用剪头函数时,有个隐式返回,注意括号。

Longhand:
//longhand
function getArea(diameter) {
return Math.PI * diameter
} //shorthand
getArea = diameter => (
Math.PI * diameter;
)

12.Lookup Conditions Shorthand

如果我们有代码来检查类型,并且基于类型需要调用不同的方法,我们可以选择使用多个 else ifs 或进行切换,但是如果我们有比这更好的方式呢?

// Longhand
if (type === 'test1') {
test1();
}
else if (type === 'test2') {
test2();
}
else if (type === 'test3') {
test3();
}
else if (type === 'test4') {
test4();
} else {
throw new Error('Invalid value ' + type);
} // Shorthand
var types = {
test1: test1,
test2: test2,
test3: test3,
test4: test4
}; var func = types[type];
(!func) && throw new Error('Invalid value ' + type); func();

13.Object.entries()

此功能有助于将对象转换为对象数组。

const data = { test1: 'abc', test2: 'cde', test3: 'efg' };
const arr = Object.entries(data);
console.log(arr); /** Output:
[ [ 'test1', 'abc' ],
[ 'test2', 'cde' ],
[ 'test3', 'efg' ]
]
**/

14. Object.values()

这也是 ES8 中引入的一项新功能,它执行与 Object.Entry () 类似的功能,但没有关键部分:

const data = { test1: 'abc', test2: 'cde' };
const arr = Object.values(data);
console.log(arr); /** Output:
[ 'abc', 'cde']
**/

15. 多次重复字符串

为了一次又一次地重复相同的字符,我们可以使用 for 循环并将它们添加到同一个循环中,但是如果我们有一个速记呢?

//longhand
let test = '';
for(let i = 0; i < 5; i ++) {
test += 'test ';
}
console.log(str); // test test test test test //shorthand
'test '.repeat(5);

16. 指数幂函数

数学指数幂函数的速记:

//longhand
Math.pow(2,3); // 8 //shorthand
2**3 // 8

17. 数字分隔符

现在,您只需使用 _ 即可轻松分隔数字。

//old syntax
let number = 98234567 //new syntax
let number = 98_234_567

结论

我们在编写代码的过程中多思考,多记录,看看哪种是最好,又是最短的方式,这样有助于提高编程水平。

其他精彩文章

最新文章

  1. opencv在图像显示中文
  2. CLR 公共语言运行库
  3. Java对象排序
  4. java判断文件是否存在
  5. JS魔法堂:doctype我们应该了解的基础知识
  6. win7 IIS 7.5 HTTP 错误 404.3 - Not Found
  7. IO流基础
  8. Codeforces 325D
  9. Asp.net 4.0,首次请求目录下的文件时响应很慢
  10. (转)经验分享:CSS浮动(float,clear)通俗讲解
  11. 【知识整理】这可能是最好的RxJava 2.x 入门教程(一)
  12. 方法重载(overroad)和方法覆盖(override)------java基础知识总结
  13. 洛谷P4570 [BJWC2011]元素 线性基
  14. C基础 - 终结 Size Balanced Tree
  15. windows设置控制台编码格式为UTF-8
  16. CF161D Distance in Tree
  17. Android Studio集成SVN报错:can&amp;#39;t use subversion command line client : svn
  18. swift user guide.pdf下载
  19. ueditor1.4.3jsp版在上传图片报&quot;未找到上传文件&quot;解决方案
  20. BZOJ 2069 POI2004 ZAW 堆优化Dijkstra

热门文章

  1. 树莓派4B智能小车机器套件——入手组装实验记录
  2. 风炫安全WEB安全学习第十九节课 XSS的漏洞基础知识和原理讲解
  3. Spring(3) --事务,隔离级别,设计模式
  4. ORACLE的还原表空间UNDO写满磁盘空间,解决该问题的具体步骤
  5. Centos7 Nginx+PHP7 配置
  6. scp传文件夹
  7. 【Linux】NFS相关小问题
  8. 【老孟Flutter】源码分析系列之InheritedWidget
  9. C语言变量
  10. 高效率同步降压变换器,24V转3.3V降压芯片