热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

【JS代码优化技巧】

不可错过的JS代码优化技巧JS代码优化技巧1.带有多个条件的if语句把多个值放在一个数组中,然后调用数组的includes方法。longhandif(x‘abc

@不可错过的JS代码优化技巧


JS代码优化技巧


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 true…else

对于不包含大逻辑的 if-else 条件,可以使用下面的快捷写法。我们可以简单地使用三元运算符来实现这种简化。


// Longhand
let test: boolean;
if (x > 100) {
test = true;
} else {
test = false;
}
// Shorthand
let test = (x > 10) ? true : false;
//或者我们也可以直接用
let test = x > 10;
console.log(test);



3. 声明变量

当我们想要声明两个具有相同的值或相同类型的变量时,可以使用这种简写。


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



4. null、undefined 和空值检查

当我们创建了新变量,有时候想要检查引用的变量是不是为非 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); // 输出 “”



6. undefined 检查和默认赋值


let test1 = undefined,
test2 = test1 || ‘’;
console.log(“undefined check”, test2); // 输出 “”
一般值检查
let test1 = ‘test’,
test2 = test1 || ‘’;
console.log(test2); // 输出: ‘test’
另外,对于上述的 4、5、6 点,都可以使用?? 操作符。


如果左边值为 null 或 undefined,就返回右边的值。默认情况下,它将返回左边的值。


const test= null ?? ‘default’;
console.log(test);
// 输出结果: “default”
const test1 = 0 ?? 2;
console.log(test1);
// 输出结果: 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. if 判断值是否存在

这是我们都在使用的一种常用的简便技巧,在这里仍然值得再提一下。


// Longhand
if (test1 === true) or if (test1 !== “”) or if (test1 !== null)
// Shorthand //检查空字符串、null或者undefined
if (test1)
注意:如果 test1 有值,将执行 if 之后的逻辑,这个操作符主要用于 null 或 undefinded 检查。



10. 用于多个条件判断的 && 操作符

如果只在变量为 true 时才调用函数,可以使用 && 操作符。


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



11. for each 循环

这是一种常见的循环简化技巧。


// Longhand
for (var i = 0; i // Shorthand
for (let i in testData) or for (let i of testData)
遍历数组的每一个变量。


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 test
function callMe(val) {
console.log(val);
}
// Shorthand
function 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 简化

我们可以将条件保存在键值对象中,并根据条件来调用它们。


// Longhand
switch (data) {
case 1:
test1();
break;
case 2:
test2();
break;
case 3:
test();
break;
// …
}
// Shorthand
var data = {
1: test1,
2: test2,
3: test
};
data[something] && datasomething;



16. 隐式返回

通过使用箭头函数,我们可以直接返回值,不需要 return 语句。


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



17. 指数表示法


// Longhand
for (var i &#61; 0; i <10000; i&#43;&#43;) { … }
// Shorthand
for (var i &#61; 0; i <1e4; i&#43;&#43;) {



18. 默认参数值


//Longhand
function add(test1, test2) {
if (test1 &#61;&#61;&#61; undefined)
test1 &#61; 1;
if (test2 &#61;&#61;&#61; undefined)
test2 &#61; 2;
return test1 &#43; test2;
}
//shorthand
add &#61; (test1 &#61; 1, test2 &#61; 2) &#61;> (test1 &#43; test2);
add() //输出结果: 3



19. 延展操作符简化


//longhand
// 使用concat连接数组
const data &#61; [1, 2, 3];
const test &#61; [4 ,5 , 6].concat(data);
//shorthand
// 连接数组
const data &#61; [1, 2, 3];
const test &#61; [4 ,5 , 6, …data];
console.log(test); // [ 4, 5, 6, 1, 2, 3]
我们也可以使用延展操作符进行克隆。



//longhand
// 克隆数组
const test1 &#61; [1, 2, 3];
const test2 &#61; test1.slice()
//shorthand
//克隆数组
const test1 &#61; [1, 2, 3];
const test2 &#61; […test1];



20. 模板字面量

如果你厌倦了使用 &#43; 将多个变量连接成一个字符串&#xff0c;那么这个简化技巧将让你不再头痛。


//longhand
const welcome &#61; &#39;Hi ’ &#43; test1 &#43; ’ ’ &#43; test2 &#43; ‘.’
//shorthand
const welcome &#61; Hi ${test1} ${test2};



21. 跨行字符串

当我们在代码中处理跨行字符串时&#xff0c;可以这样做。


//longhand
const data &#61; ‘abc abc abc abc abc abc\n\t’
&#43; ‘test test,test test test test\n\t’
//shorthand
const data &#61; abc abc abc abc abc abc test test,test test test test



22. 对象属性赋值

?let test1 &#61; ‘a’;
let test2 &#61; ‘b’;
//Longhand
let obj &#61; {test1: test1, test2: test2};
//Shorthand
let obj &#61; {test1, test2};


23. 将字符串转成数字


//Longhand
let test1 &#61; parseInt(‘123’);
let test2 &#61; parseFloat(‘12.3’);
//Shorthand
let test1 &#61; &#43;‘123’;
let test2 &#61; &#43;‘12.3’;



24. 解构赋值


//longhand
const test1 &#61; this.data.test1;
const test2 &#61; this.data.test2;
const test2 &#61; this.data.test3;
//shorthand
const { test1, test2, test3 } &#61; this.data;



25. 数组 find 简化

当我们有一个对象数组&#xff0c;并想根据对象属性找到特定对象&#xff0c;find 方法会非常有用。


const data &#61; [{
type: ‘test1’,
name: ‘abc’
},
{
type: ‘test2’,
name: ‘cde’
},
{
type: ‘test1’,
name: ‘fgh’
},
]
function findtest1(name) {
for (let i &#61; 0; i if (data[i].type &#61;&#61;&#61; ‘test1’ && data[i].name &#61;&#61;&#61; name) {
return data[i];
}
}
}
//Shorthand
filteredData &#61; data.find(data &#61;> data.type &#61;&#61;&#61; ‘test1’ && data.name &#61;&#61;&#61; ‘fgh’);
console.log(filteredData); // { type: ‘test1’, name: ‘fgh’ }



26. 条件查找简化

如果我们要基于不同的类型调用不同的方法&#xff0c;可以使用多个 else if 语句或 switch&#xff0c;但有没有比这更好的简化技巧呢&#xff1f;


// Longhand
if (type &#61;&#61;&#61; ‘test1’) {
test1();
}
else if (type &#61;&#61;&#61; ‘test2’) {
test2();
}
else if (type &#61;&#61;&#61; ‘test3’) {
test3();
}
else if (type &#61;&#61;&#61; ‘test4’) {
test4();
} else {
throw new Error(&#39;Invalid value ’ &#43; type);
}
// Shorthand
var types &#61; {
test1: test1,
test2: test2,
test3: test3,
test4: test4
};
var func &#61; types[type];
(!func) && throw new Error(&#39;Invalid value ’ &#43; type); func();



27. indexOf 的按位操作简化

在查找数组的某个值时&#xff0c;我们可以使用 indexOf() 方法。但有一种更好的方法&#xff0c;让我们来看一下这个例子。


//longhand
if(arr.indexOf(item) > -1) { // item found
}
if(arr.indexOf(item) &#61;&#61;&#61; -1) { // item not found
}
//shorthand
if(~arr.indexOf(item)) { // item found
}
if(!~arr.indexOf(item)) { // item not found
}
按位 ( ~ ) 运算符将返回 true&#xff08;-1 除外&#xff09;&#xff0c;反向操作只需要!~。另外&#xff0c;也可以使用 include() 函数。



if (arr.includes(item)) {
// 如果找到项目&#xff0c;则为true
}



28. Object.entries()

这个方法可以将对象转换为对象数组。


const data &#61; { test1: ‘abc’, test2: ‘cde’, test3: ‘efg’ };
const arr &#61; Object.entries(data);
console.log(arr);
/** Output:
[ [ ‘test1’, ‘abc’ ],
[ ‘test2’, ‘cde’ ],
[ ‘test3’, ‘efg’ ]
]
**/



29. Object.values()

这也是 ES8 中引入的一个新特性&#xff0c;它的功能类似于 Object.entries()&#xff0c;只是没有键。


const data &#61; { test1: ‘abc’, test2: ‘cde’ };
const arr &#61; Object.values(data);
console.log(arr);
/** Output:
[ ‘abc’, ‘cde’]
**/



30. 双重按位操作


// Longhand
Math.floor(1.9) &#61;&#61;&#61; 1 // true
// Shorthand
~~1.9 &#61;&#61;&#61; 1 // true



31. 重复字符串多次

为了重复操作相同的字符&#xff0c;我们可以使用 for 循环&#xff0c;但其实还有一种简便的方法。


//longhand
let test &#61; ‘’;
for(let i &#61; 0; i <5; i &#43;&#43;) {
test &#43;&#61; &#39;test &#39;;
}
console.log(str); // test test test test test
//shorthand
&#39;test &#39;.repeat(5);



32. 查找数组的最大值和最小值


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



33. 获取字符串的字符


let str &#61; ‘abc’;
//Longhand
str.charAt(2); // c
//Shorthand
str[2]; // c



34. 指数幂简化


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


源自&#xff1a;https://juejin.cn/post/7078575191244144670
声明&#xff1a;文章著作权归作者所有&#xff0c;如有侵权&#xff0c;请联系删除。


推荐阅读
  • Iamtryingtomakeaclassthatwillreadatextfileofnamesintoanarray,thenreturnthatarra ... [详细]
  • 本文介绍了使用Java实现大数乘法的分治算法,包括输入数据的处理、普通大数乘法的结果和Karatsuba大数乘法的结果。通过改变long类型可以适应不同范围的大数乘法计算。 ... [详细]
  • Java序列化对象传给PHP的方法及原理解析
    本文介绍了Java序列化对象传给PHP的方法及原理,包括Java对象传递的方式、序列化的方式、PHP中的序列化用法介绍、Java是否能反序列化PHP的数据、Java序列化的原理以及解决Java序列化中的问题。同时还解释了序列化的概念和作用,以及代码执行序列化所需要的权限。最后指出,序列化会将对象实例的所有字段都进行序列化,使得数据能够被表示为实例的序列化数据,但只有能够解释该格式的代码才能够确定数据的内容。 ... [详细]
  • Java容器中的compareto方法排序原理解析
    本文从源码解析Java容器中的compareto方法的排序原理,讲解了在使用数组存储数据时的限制以及存储效率的问题。同时提到了Redis的五大数据结构和list、set等知识点,回忆了作者大学时代的Java学习经历。文章以作者做的思维导图作为目录,展示了整个讲解过程。 ... [详细]
  • LeetCode笔记:剑指Offer 41. 数据流中的中位数(Java、堆、优先队列、知识点)
    本文介绍了LeetCode剑指Offer 41题的解题思路和代码实现,主要涉及了Java中的优先队列和堆排序的知识点。优先队列是Queue接口的实现,可以对其中的元素进行排序,采用小顶堆的方式进行排序。本文还介绍了Java中queue的offer、poll、add、remove、element、peek等方法的区别和用法。 ... [详细]
  • 本文介绍了如何在给定的有序字符序列中插入新字符,并保持序列的有序性。通过示例代码演示了插入过程,以及插入后的字符序列。 ... [详细]
  • 本文讨论了一个关于cuowu类的问题,作者在使用cuowu类时遇到了错误提示和使用AdjustmentListener的问题。文章提供了16个解决方案,并给出了两个可能导致错误的原因。 ... [详细]
  • 判断数组是否全为0_连续子数组的最大和的解题思路及代码方法一_动态规划
    本文介绍了判断数组是否全为0以及求解连续子数组的最大和的解题思路及代码方法一,即动态规划。通过动态规划的方法,可以找出连续子数组的最大和,具体思路是尽量选择正数的部分,遇到负数则不选择进去,遇到正数则保留并继续考察。本文给出了状态定义和状态转移方程,并提供了具体的代码实现。 ... [详细]
  • 本文详细介绍了Java中vector的使用方法和相关知识,包括vector类的功能、构造方法和使用注意事项。通过使用vector类,可以方便地实现动态数组的功能,并且可以随意插入不同类型的对象,进行查找、插入和删除操作。这篇文章对于需要频繁进行查找、插入和删除操作的情况下,使用vector类是一个很好的选择。 ... [详细]
  • 猜字母游戏
    猜字母游戏猜字母游戏——设计数据结构猜字母游戏——设计程序结构猜字母游戏——实现字母生成方法猜字母游戏——实现字母检测方法猜字母游戏——实现主方法1猜字母游戏——设计数据结构1.1 ... [详细]
  • [大整数乘法] java代码实现
    本文介绍了使用java代码实现大整数乘法的过程,同时也涉及到大整数加法和大整数减法的计算方法。通过分治算法来提高计算效率,并对算法的时间复杂度进行了研究。详细代码实现请参考文章链接。 ... [详细]
  • 本文详细介绍了GetModuleFileName函数的用法,该函数可以用于获取当前模块所在的路径,方便进行文件操作和读取配置信息。文章通过示例代码和详细的解释,帮助读者理解和使用该函数。同时,还提供了相关的API函数声明和说明。 ... [详细]
  • 电话号码的字母组合解题思路和代码示例
    本文介绍了力扣题目《电话号码的字母组合》的解题思路和代码示例。通过使用哈希表和递归求解的方法,可以将给定的电话号码转换为对应的字母组合。详细的解题思路和代码示例可以帮助读者更好地理解和实现该题目。 ... [详细]
  • 本文介绍了设计师伊振华受邀参与沈阳市智慧城市运行管理中心项目的整体设计,并以数字赋能和创新驱动高质量发展的理念,建设了集成、智慧、高效的一体化城市综合管理平台,促进了城市的数字化转型。该中心被称为当代城市的智能心脏,为沈阳市的智慧城市建设做出了重要贡献。 ... [详细]
  • Spring特性实现接口多类的动态调用详解
    本文详细介绍了如何使用Spring特性实现接口多类的动态调用。通过对Spring IoC容器的基础类BeanFactory和ApplicationContext的介绍,以及getBeansOfType方法的应用,解决了在实际工作中遇到的接口及多个实现类的问题。同时,文章还提到了SPI使用的不便之处,并介绍了借助ApplicationContext实现需求的方法。阅读本文,你将了解到Spring特性的实现原理和实际应用方式。 ... [详细]
author-avatar
仁寿戴氏
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有