2025年4月15日 星期二 乙巳(蛇)年 正月十六 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > JavaScript

18个你需要知道的 JavaScript 优化技巧

时间:11-10来源:作者:点击数:33

本文来源于个人多年的 JavaScript 编码技术经验,适合所有正在使用 JavaScript 编程的开发人员阅读。

本文的目的在于帮助大家更加熟练的运用 JavaScript 语言来进行开发工作。

1. 多个条件的判断

当我们需要进行多个值的判断时,我们可以使用数组的includes方法。

  • //Bad
  • if (x === 'iphoneX' || x === 'iphone11' || x === 'iphone12') {
  • //code...
  • }
  • //Good
  • if (['iphoneX', 'iphone11', 'iphone12'].includes(x)) {
  • //code...
  • }

2. If true … else

if-else条件的内部不包含更大的逻辑时,三目运算符会更好。

  • // Bad
  • let test= boolean;
  • if (x > 100) {
  • test = true;
  • } else {
  • test = false;
  • }
  • // Good
  • let test = (x > 10) ? true : false;
  • //or we can simply use
  • let test = x > 10;

嵌套条件后,我们保留如下所示的内容(复杂点的三目):

  • 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、‘’ 空值检查

有时要检查我们为值引用的变量是否不为nullUndefined 或 '' ,我们可以使用短路写法

  • // Bad
  • if (first !== null || first !== undefined || first !== '') {
  • let second = first;
  • }
  • // Good 短路写法
  • let second = first|| '';

4. 空值检查和分配默认值

当我们赋值,发现变量为空需要分配默认值 可以使用以下短路写法

  • let first = null,
  • let second = first || 'default'
  • console.log(second)

4. 双位操作符

位操作符是 JavaScript 初级教程的基本知识点,但是我们却不常使用位操作符。因为在不处理二进制的情况下,没有人愿意使用 1 和 0。

但是双位操作符却有一个很实用的案例。你可以使用双位操作符来替代 Math.floor( )。双否定位操作符的优势在于它执行相同的操作运行速度更快

  • // Bad
  • Math.floor(4.9) === 4 //true
  • // Good
  • ~~4.9 === 4 //true

5. ES6常见小优化 - 对象属性

  • const x,y = 5
  • // Bad
  • const obj = { x:x, y:y }
  • // Good
  • const obj = { x, y }

6. ES6常见小优化-箭头函数

  • //Bad
  • function sayHello(name) {
  • console.log('Hello', name);
  • }
  • setTimeout(function() {
  • console.log('Loaded')
  • }, 2000)
  • list.forEach(function(item) {
  • console.log(item)
  • })
  • // Good
  • const sayHello = name => console.log('Hello', name)
  • setTimeout(() => console.log('Loaded'), 2000)
  • list.forEach(item => console.log(item))

7. ES6常见小优化-隐式返回值

返回值是我们通常用来返回函数最终结果的关键字。只有一个语句的箭头函数,可以隐式返回结果(函数必须省略括号({ }),以便省略返回关键字)。

要返回多行语句(例如对象文本),需要使用()而不是{ }来包裹函数体。这样可以确保代码以单个语句的形式进行求值。

  • //Bad
  • function calcCircumference(diameter) {
  • return Math.PI * diameter
  • }
  • // Good
  • const calcCircumference = diameter => (
  • Math.PI * diameter
  • )

8. ES6常见小优化-解构赋值

  • const form = { a:1, b:2, c:3 }
  • //Bad
  • const a = form.a
  • const b = form.b
  • const c = form.c
  • // Good
  • const { a, b, c } = form

9. ES6常见小优化-展开运算符

返回值是我们通常用来返回函数最终结果的关键字。只有一个语句的箭头函数,可以隐式返回结果(函数必须省略括号({ }),以便省略返回关键字)。

要返回多行语句(例如对象文本),需要使用()而不是{ }来包裹函数体。这样可以确保代码以单个语句的形式进行求值。

  • const odd = [ 1, 3, 5 ]
  • const arr = [ 1, 2, 3, 4 ]
  • // Bad
  • const nums = [ 2, 4, 6 ].concat(odd)
  • const arr2 = arr.slice( )
  • // Good
  • const nums = [2 ,4 , 6, ...odd]
  • const arr2 = [...arr]

10. 数组常见处理

掌握数组常见方法,记在脑子里,不要写的时候再去看API了,这样可以有效提升编码效率,毕竟这些方法每天都在用

every some filter map forEach find findIndex reduce includes

  • const arr = [1,2,3]
  • //every 每一项都成立,才会返回true
  • arr.every(it => it>0 ) //true
  • //some 有一项都成了,就会返回true
  • arr.some(it => it>2 ) //true
  • //filter 过滤器
  • arr.filter(it => it===2 ) //[2]
  • //map 返回一个新数组
  • arr.map(it => ({id:it}) ) //[ {id:1},{id:2},{id:3} ]
  • //forEach 没有返回值
  • arr.forEach(it => it===console.log(it)) //1,2,3
  • //find 查找对应值 找到就立马返回符合要求的新数组
  • arr.find(it => it>2) //3
  • //findIndex 查找对应值 找到就立马返回符合要求新数组的下标
  • arr.findIndex(it => it>2) //2
  • //reduce 求和或者合并数组
  • arr.reduce((prev,cur) => prev+cur) //6
  • //includes 求和或者合并数组
  • arr.includes(1) //true
  • //数组去重
  • const arr1 = [1,2,3,3]
  • const removeRepeat = (arr) => [...new Set(arr1)]//[1,2,3]
  • //数组求最大值
  • Math.max(...arr)//3
  • Math.min(...arr)//1
  • //对象解构 这种情况也可以使用Object.assign代替
  • let defaultParams={
  • pageSize:1,
  • sort:1
  • }
  • //goods1
  • let reqParams={
  • ...defaultParams,
  • sort:2
  • }
  • //goods2
  • Object.assign( defaultParams, {sort:2} )

11. 比较返回

return语句中使用比较可以将代码从5行减少到1行。

  • // Bad
  • let test
  • const checkReturn = () => {
  • if (test !== undefined) {
  • return test;
  • } else {
  • return callMe('test');
  • }
  • }
  • // Good
  • const checkReturn = () => {
  • return test || callMe('test');
  • }

12. 短函数调用

我们可以使用三元运算符来实现这类函数。

  • const test1 =() => {
  • console.log('test1');
  • }
  • const test2 =() => {
  • console.log('test2');
  • }
  • const test3 = 1;
  • if (test3 == 1) {
  • test1()
  • } else {
  • test2()
  • }
  • // Good
  • test3 === 1? test1():test2()

13.switch代码块(ifelse代码块)简写

我们可以将条件保存在key-value对象中,然后可以根据条件使用。

  • // Bad
  • switch (data) {
  • case 1:
  • test1();
  • break;
  • case 2:
  • test2();
  • break;
  • case 3:
  • test();
  • break;
  • // And so on...
  • }
  • // Good
  • const data = {
  • 1: test1,
  • 2: test2,
  • 3: test
  • }
  • data[anything] && data[anything]()
  • // Bad
  • 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);
  • }
  • // Good
  • const types = {
  • test1: test1,
  • test2: test2,
  • test3: test3,
  • test4: test4
  • };
  • const func = types[type];
  • (!func) && throw new Error('Invalid value ' + type); func();

14. 多行字符串简写

当我们在代码中处理多行字符串时,可以这样做:

  • // Bad
  • const data = 'abc abc abc abc abc abc\n\t'
  • + 'test test,test test test test\n\t'
  • // Good
  • const data = `abc abc abc abc abc abc
  • test test,test test test test`

15. Object.entries() Object.values() Object.keys()

Object.entries() 该特性可以将一个对象转换成一个对象数组。

Object.values()可以拿到对象value值

Object.keys()可以拿到对象key值

  • const data = { test1: 'abc', test2: 'cde' }
  • const arr1 = Object.entries(data)
  • const arr2 = Object.values(data)
  • const arr3 = Object.keys(data)
  • /** arr1 Output:
  • [
  • [ 'test1', 'abc' ],
  • [ 'test2', 'cde' ],
  • ]
  • **/
  • /** arr2 Output:
  • ['abc', 'cde']
  • **/
  • /** arr3 Output:
  • ['test1', 'test2']
  • **/

16. 多次重复一个字符串

为了多次重复相同的字符,我们可以使用for循环并将它们添加到同一个循环中,如何简写呢?

  • //Bad
  • let test = '';
  • for(let i = 0; i < 5; i ++) {
  • test += 'test,';
  • }
  • console.log(str);// test,test,test,test,test,
  • //good
  • console.log('test,'.repeat(5))

17. 幂的简写

数学指数幂函数的good如下:

  • //Bad
  • Math.pow(2,3)// 8
  • //good
  • 2**3 // 8

18. 数字分隔符

你现在只需使用 _ 即可轻松分隔数字。这将使处理大量数据变得更加轻松。

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

如果你想使用JavaScript最新版本(ES2021/ES12)的最新功能,请检查以下内容:

1.replaceAll():返回一个新字符串,其中所有匹配的模式都被新的替换词替换。

2.Promise.any():需要一个可迭代的Promise对象,当一个Promise完成时,返回一个带有值的Promise。

3.weakref:此对象持有对另一个对象的弱引用,不阻止该对象被垃圾收集。

4.FinalizationRegistry:让你在对象被垃圾回收时请求回调。

5.私有方法:方法和访问器的修饰符:私有方法可以用#声明。

6.逻辑运算符:&&||运算符。

7.Intl.ListFormat:此对象启用对语言敏感的列表格式。

8.Intl.DateTimeFormat:该对象启用对语言敏感的日期和时间格式。

方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门
本栏推荐