34 个 JavaScript 代码优化技巧

Souleigh ✨
• 阅读 1218

1. 含有多个条件的 if 语句

我们可以在数组中存储多个值,并且可以使用数组的 includes 方法。

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

2. If … 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 use directly  
let test = x > 10;console.log(test);  

如果包含嵌套的条件,我们也可以这样写。

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

3. 定义变量

当我们定义两个值相同或类型相同的变量,可以使用这样的缩写法

//Longhand   
let test1;  
let test2 = 1;  
//Shorthand   
let test1, test2 = 1;  

4. 对 Null、Undefined、Empty 这些值的检查

我们创建一个新变量,有时候需要检查是否为 Null 或 Undefined。JavaScript 本身就有一种缩写法能实现这种功能。

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

5. 对 Null 值的检查以及默认赋值

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

6. 对 Undefined 值的检查以及默认赋值

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

对正常值的检查

let test1 = 'test',  
    test2 = test1 || '';console.log(test2); // output: 'test'  

利好消息:关于第 4、5、6 条还可以使用 ?? 运算符

聚合运算符

**??**是聚合运算符,如果左值为 null 或 undefined,就返回右值。默认返回左值。

const test= null ?? 'default';  
console.log(test);  
// expected output: "default"const test1 = 0 ?? 2;  
console.log(test1);  
// expected output: 0  

7. 同时为多个变量赋值

当我们处理多个变量,并且需要对这些变量赋不同的值,这种缩写法很有用。

//Longhand   
let test1, test2, test3;  
test1 = 1;  
test2 = 2;  
test3 = 3;  
//Shorthand   
let [test1, test2, test3] = [1, 2, 3];  

8. 赋值运算符缩写法

编程中使用算术运算符是很常见的情况。以下是 JavaScript 中赋值运算符的应用。

// Longhand  
test1 = test1 + 1;  
test2 = test2 - 1;  
test3 = test3 * 20;  
// Shorthand  
test1++;  
test2--;  
test3 *= 20;  

9. 判断变量是否存在的缩写法

这是普遍使用的缩写法,但在这里应当提一下。

// Longhand  
if (test1 === true) or if (test1 !== "") or if (test1 !== null)  

// Shorthand   
//it will check empty string,null and undefined too  
if (test1)  

注意:当 test1 为任何值时,程序都会执行 if(test1){ } 内的逻辑,这种写法在判断 NULL 或 undefined 值时普遍使用。

10. 用于多个条件的与(&&)运算符

如果需要实现某个变量为 true 时调用一个函数,可以使用 && 运算符。

//Longhand   
if (test1) {  
 callMethod();   
} //Shorthand   
test1 && callMethod();  

11. foreach 循环缩写法

这是循环结构对应的缩写法。

// Longhand  
for (var i = 0; i < testData.length; i++)  

// Shorthand  
for (let i in testData) or  for (let i of testData)  

Array for each variable

function testData(element, index, array) {  
  console.log('test[' + index + '] = ' + element);  
}  

[11, 24, 32].forEach(testData);  
// logs: test[0] = 11, test[1] = 24, test[2] = 32  

12. 比较结果的返回

在 return 语句中,我们也可以使用比较的语句。这样,原来需要 5 行代码才能实现的功能,现在只需要 1 行,大大减少了代码量。

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

13. 箭头函数

//Longhand   
function add(a, b) {   
   return a + b;   
}   
//Shorthand   
const add = (a, b) => a + b;  

再举个例子

function callMe(name) {  
  console.log('Hello', name);  
}callMe = name => console.log('Hello', name);  

14. 简短的函数调用语句

我们可以使用三元运算符实现如下功能。

// 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)();  

15. 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[something] && data[something]();  

16. 隐式返回缩写法

使用箭头函数,我们可以直接得到函数执行结果,不需要写 return 语句。

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

17. 十进制数的指数形式

// Longhand  
for (var i = 0; i < 10000; i++) { ... }  

// Shorthand  
for (var i = 0; i < 1e4; i++) {  

18. 默认参数值

//Longhand  
function add(test1, test2) {  
  if (test1 === undefined)  
    test1 = 1;  
  if (test2 === undefined)  
    test2 = 2;  
  return test1 + test2;  
}  
//shorthand  
add = (test1 = 1, test2 = 2) => (test1 + test2);add() //output: 3  

19. 延展操作符的缩写法

//longhand// joining arrays using concat  
const data = [1, 2, 3];  
const test = [4 ,5 , 6].concat(data);  
//shorthand// joining arrays  
const data = [1, 2, 3];  
const test = [4 ,5 , 6, ...data];  
console.log(test); // [ 4, 5, 6, 1, 2, 3]  

我们也可以使用延展操作符来克隆。

//longhand  

// cloning arrays  
const test1 = [1, 2, 3];  
const test2 = test1.slice()  
//shorthand  

// cloning arrays  
const test1 = [1, 2, 3];  
const test2 = [...test1];  

20. 文本模板

如果你对使用 + 符号来连接多个变量感到厌烦,这个缩写法可以帮到你。

`//longhand  
const welcome = 'Hi ' + test1 + ' ' + test2 + '.'  
//shorthand  
const welcome = `Hi ${test1} ${test2}`;  

21. 跟多行文本有关的缩写法

当我们在代码中处理多行文本时,可以使用这样的技巧

`//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`  

22. 对象属性的赋值

let test1 = 'a';   
let test2 = 'b';  
//Longhand   
let obj = {test1: test1, test2: test2};   
//Shorthand   
let obj = {test1, test2};  

23. 字符串转换为数字

//Longhand   
let test1 = parseInt('123');   
let test2 = parseFloat('12.3');   
//Shorthand   
let test1 = +'123';   
let test2 = +'12.3';  

24. 解构赋值缩写法

//longhand  
const test1 = this.data.test1;  
const test2 = this.data.test2;  
const test2 = this.data.test3;  
//shorthand  
const { test1, test2, test3 } = this.data;  

25. Array.find 缩写法

当我们需要在一个对象数组中按属性值查找特定对象时,find 方法很有用。

const data = [{  
        type: 'test1',  
        name: 'abc'  
    },  
    {  
        type: 'test2',  
        name: 'cde'  
    },  
    {  
        type: 'test1',  
        name: 'fgh'  
    },  
]function findtest1(name) {  
    for (let i = 0; i < data.length; ++i) {  
        if (data[i].type === 'test1' && data[i].name === name) {  
            return data[i];  
        }  
    }  
}  
//Shorthand  
filteredData = data.find(data => data.type === 'test1' && data.name === 'fgh');  
console.log(filteredData); // { type: 'test1', name: 'fgh' }  

26. 查询条件缩写法

如果我们要检查类型,并根据类型调用不同的函数,我们既可以使用多个 else if 语句,也可以使用 switch,除此之外,如果有缩写法,代码会是怎么样呢?

// 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();  

27. 按位非和 indexOf 缩写法

我们以查找特定值为目的迭代一个数组,通常用到 indexOf() 方法。

//longhand  
if(arr.indexOf(item) > -1) { // item found   
}  
if(arr.indexOf(item) === -1) { // item not found  
}  
//shorthand  
if(~arr.indexOf(item)) { // item found  
}  
if(!~arr.indexOf(item)) { // item not found  
}  

对除 -1 外的任何数进行 按位非(~) 运算都会返回真值。把按位非的结果再次进行逻辑取反就是 !~,这非常简单。或者我们也可以使用 includes() 函数:

if (arr.includes(item)) {   
// true if the item found  
}  

28. 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' ]  
]  
**/  

29. Object.values()

这也是 ES8 中介绍的一个新特性,它的功能与 Object.entries() 类似,但没有其核心功能:

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

30. 两个位运算符缩写

(两个按位非运算符只适用于 32 位整型)

// Longhand  
Math.floor(1.9) === 1 // true  

// Shorthand  
~~1.9 === 1 // true  

31. 把一个字符串重复多次

我们可以使用 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);  

32. 找出一个数组中最大和最小的值

const arr = [1, 2, 3];   
Math.max(…arr); // 3  
Math.min(…arr); // 1  

33. 获取字符串中的字符

let str = 'abc';  
//Longhand   
str.charAt(2); // c  
//Shorthand   
//注意:如果事先知道目标字符在字符串中的索引,我们可以直接使用该索引值。如果索引值不确定,运行时就有可能抛出 undefined。  
str[2]; // c  

34. 幂运算的缩写法

指数幂函数的缩写法:

//longhand  
Math.pow(2,3); // 8  
//shorthand  
2**3 // 8  
点赞
收藏
评论区
推荐文章
blmius blmius
2年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Karen110 Karen110
2年前
一篇文章带你了解JavaScript日期
日期对象允许您使用日期(年、月、日、小时、分钟、秒和毫秒)。一、JavaScript的日期格式一个JavaScript日期可以写为一个字符串:ThuFeb02201909:59:51GMT0800(中国标准时间)或者是一个数字:1486000791164写数字的日期,指定的毫秒数自1970年1月1日00:00:00到现在。1\.显示日期使用
Jacquelyn38 Jacquelyn38
2年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
凝雪探世界 凝雪探世界
3年前
2021年你需要了解的13 种JavaScript 代码技巧
1\.多表达式多if判断我们可以在数组中存储多个值,并且可以使用数组include方法。//长if(x'abc'||x'def'||x'ghi'||x'jkl'){//logic}//短if('abc','def','ghi','jkl'
Stella981 Stella981
2年前
Android So动态加载 优雅实现与原理分析
背景:漫品Android客户端集成适配转换功能(基于目标识别(So库35M)和人脸识别库(5M)),导致apk体积50M左右,为优化客户端体验,决定实现So文件动态加载.!(https://oscimg.oschina.net/oscnet/00d1ff90e4b34869664fef59e3ec3fdd20b.png)点击上方“蓝字”关注我
Wesley13 Wesley13
2年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Stella981 Stella981
2年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Wesley13 Wesley13
2年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
3个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这