我们经常会写一些 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

结论

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

其他精彩文章

2021 年写 JavaScript 代码的 17 个优化技巧的更多相关文章

  1. 如何写javascript代码隐藏和显示这个div

    如何写javascript代码隐藏和显示这个div 浏览次数:82次悬赏分:10 | 解决时间:2011-4-21 14:41 | 提问者:hade_girl <div id="div ...

  2. 编写JavaScript 代码的5个小技巧

    1.Array.includes 与条件判断 一般我们判断或用 || // condition function test(fruit) { if (fruit == "apple" ...

  3. 写好Hive 程序的若干优化技巧和实际案例

    使用Hive可以高效而又快速地编写复杂的MapReduce查询逻辑.但是一个”好”的Hive程序需要对Hive运行机制有深入的了解,像理解mapreduce作业一样理解Hive QL才能写出正确.高效 ...

  4. 使用 TypeScript & mocha & chai 写测试代码实战(17 个视频)

    使用 TypeScript & mocha & chai 写测试代码实战(17 个视频) 使用 TypeScript & mocha & chai 写测试代码实战 #1 ...

  5. FineUI(专业版)实现百变通知框(无JavaScript代码)!

    博客园已经越来越不公正了,居然说我这篇文章没有实质的内容!! 我其实真的想问哪些通篇几十个字,没任何代码和技术分享,嚷嚷着送书的文章的就能雄霸博客园首页几天,我这篇文章偏偏就为管理员所容不下. 其实我 ...

  6. 【译】写好JavaScript条件语句的5个技巧

    译文 当我们写JavaScript代码时,经常会用到到条件判断处理,这里有5个技巧能使你写出更好.更简洁的条件语句. 1.使用Array.includes处理多种条件 让我们来看一下的例子: // c ...

  7. smarty模板文件书写javascript代码

    在smarty文件里直接写javascript代码时候,造成500错误. javascript代码有很多的{}在同一行,而{}也是smarty引擎解析模板的关键标识符,smarty将对其进行分析,这时 ...

  8. How Javascript works (Javascript工作原理) (二) 引擎,运行时,如何在 V8 引擎中书写最优代码的 5 条小技巧

    个人总结: 一个Javascript引擎由一个标准解释程序,或者即时编译器来实现. 解释器(Interpreter): 解释一行,执行一行. 编译器(Compiler): 全部编译成机器码,统一执行. ...

  9. 大量javascript代码的项目如何改善可维护性

    项目中有点javascript文件,javascript代码行数达到7000多行,维护很费力,主要体现在以下几个方面: 1,方法没有注释,没有注释方法的作用,从上到下罗列,很难知道这个方法应该啥时候调 ...

随机推荐

  1. Mac上“您没有权限来打开应用程序”(Big Sur)

    最近电脑更新了Macos的最新11版大苏尔 Big Sur.很快问题就出现了:安装某个软件的时候Key Gen打不开,提示您没有权限来打开应用程序,类似这样:https://zhuanlan.zhih ...

  2. pyi文件是干嘛的?(一文读懂Python的存根文件和类型检查)

    参考资料: https://blog.csdn.net/weixin_40908748/article/details/106252884 https://www.python.org/dev/pep ...

  3. Mysql数据类型以及特性,,,防止SQL注入

    MyISAM.InnoDB.HEAP.BOB,ARCHIVE,CSV等 MyISAM:成熟.稳定.易于管理,快速读取.一些功能不支持(事务等),表级锁. InnoDB:支持事务.外键等特性.数据行锁定 ...

  4. kubernets之计算资源

    一  为pod分配cpu,内存以及其他的资源 1.1  创建一个pod,同时为这个pod分配内存以及cpu的资源请求量 apiVersion: v1 kind: Pod metadata: name: ...

  5. python3.8.1安装cx_Freeze

    按照官网的提示命令python -m pip install cx_Freeze --upgrade安装,不成功,报了一个错误,说cx_Freeze找不到需要的版本,还有一些警告说PIP需要升级,没理 ...

  6. Ice系列--强大如我IceGrid

    前言 IceGrid是一个提供服务定位和服务激活的组件,但它的功能远不止于此.从它的命名可以看出它的设计理念-网格计算(grid computing).网格计算被定义为由一系列关联的廉价计算机组成的计 ...

  7. 【转】Js中的window.parent ,window.top,window.self 详解

    [转自]http://blog.csdn.net/zdwzzu2006/article/details/6047632 在应用有frameset或者iframe的页面时,parent是父窗口,top是 ...

  8. Docker镜像仓库Harbor安装

    export VERSION=18.06 && curl -fsSL http://rainbond-pkg.oss-cn-shanghai.aliyuncs.com/releases ...

  9. Java安全之ysoserial-JRMP模块分析(一)

    Java安全之ysoserial-JRMP模块分析(一) 首发安全客:Java安全之ysoserial-JRMP模块分析(一) 0x00 前言 在分析到Weblogic后面的一些绕过方式的时候,分析到 ...

  10. 阿里 Mock 工具正式开源,干掉市面上所有 Mock 工具!

    最近栈长注意到阿里开源了自家的 Mock 工具:TestableMock,该工具号称最轻量.简单.舒适的 Mock 测试工具,功能十分强大,媲美 PowerMock,用法比 Mockito 还要简洁, ...