• 10 个JavaScript 代码优化写法技巧(适合初学者)


    1、合并数组

    正常代码:

    
    let apples = ['🍎', '🍏'];
    let fruits = ['🍉', '🍊', '🍇'].concat(apples);
    
    console.log( fruits );
    //=> ["🍉", "🍊", "🍇", "🍎", "🍏"];
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    修改后的代码:

    
    let apples = ['🍎', '🍏'];
    let fruits = ['🍉', '🍊', '🍇', ...apples];  // <-- here
    
    console.log( fruits );
    //=> ["🍉", "🍊", "🍇", "🍎", "🍏"];
    
    let apples = ['🍎', '🍏'];
    let fruits = [...apples, '🥭', '🍌', '🍒'];  // <-- here
    
    console.log( fruits );
    //=> ["🍎", "🍏", "🥭", "🍌", "🍒"];
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    2、 从数组中获取值

    正常代码:

    let apples = ['🍎', '🍏'];
    let redApple = apples[0];
    let greenApple = apples[1];
    
    console.log( redApple );    //=> 🍎
    console.log( greenApple );  //=> 🍏;
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    使用数组解构的干净代码:

    let apples = ['🍎', '🍏'];
    let [redApple, greenApple] = apples;  // <-- here
    
    console.log( redApple );    //=> 🍎
    console.log( greenApple );  //=> 🍏;
    
    • 1
    • 2
    • 3
    • 4
    • 5

    3、从对象中获取价值

    正常代码:

    let user = {
      "name": "bytefish",
      "age": 99
    }
    
    let name = user.name
    let age = user.age
    
    console.log( name );
    console.log( age );;
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    使用对象解构的干净代码:

    let user = {
      "name": "bytefish",
      "age": 99
    }
    
    let {name, age} = user
    
    console.log( name );
    console.log( age );;
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    4、循环数组

    正常代码:

    let fruits = ['🍉', '🍊', '🍇', '🍎'];
    
    for (let i = 0; i < fruits.length; i++){
      console.log(fruits[i])
    };
    
    • 1
    • 2
    • 3
    • 4
    • 5

    使用 for of 后的代码:

    let fruits = ['🍉', '🍊', '🍇', '🍎'];
    
    for (fruit of fruits) {
      console.log(fruit)
    };
    
    • 1
    • 2
    • 3
    • 4
    • 5

    5、使用箭头函数作为回调

    正常代码:

    let fruits = ['🍉', '🍊', '🍇', '🍎'];
    
    // Using forEach method
    fruits.forEach(function(fruit){
      console.log( fruit );
    });;
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    使用箭头函数清理代码:

    let fruits = ['🍉', '🍊', '🍇', '🍎'];
    fruits.forEach(fruit => console.log( fruit ));;
    
    • 1
    • 2

    注意:在处理这个时,箭头函数与普通函数不同。如果你在你的函数中使用它,不要贸然替换它。

    6、在数组中查找一项

    假设我们需要通过一个对象的属性从一个对象数组中查找一个对象,我们通常使用 for 循环:

    let inventory = [
      {name: 'Bananas', quantity: 5},
      {name: 'Apples', quantity: 10},
      {name: 'Grapes', quantity: 2}
    ];
    
    // Get the object with the name `Apples` inside the array
    function getApples(arr, value) {
      for (let index = 0; index < arr.length; index++) {
    
        // Check the value of this object property `name` is same as 'Apples'
        if (arr[index].name === 'Apples') {  //=> 🍎
    
          // A match was found, return this object
          return arr[index];
        }
      }
    }
    
    let result = getApples(inventory);
    console.log( result )
    //=> { name: "Apples", quantity: 10 };
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    使用 array.find() 清理代码:

    let inventory = [
      {name: 'Bananas', quantity: 5},
      {name: 'Apples', quantity: 10},
      {name: 'Grapes', quantity: 2}
    ];
    
    // Get the object with the name `Apples` inside the array
    function getApples(arr, value) {
      return arr.find(obj => obj.name === 'Apples');  // <-- here
    }
    
    let result = getApples(inventory);
    console.log( result )
    //=> { name: "Apples", quantity: 10 };
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    7、将字符串转换为数字

    正常代码:

    let num = parseInt("10")
    
    console.log( num )         //=> 10
    console.log( typeof num )  //=> "number";
    
    • 1
    • 2
    • 3
    • 4

    通过在字符串前添加 + 来清理代码:

    let num = +"10";
    
    console.log( num )           //=> 10
    console.log( typeof num )    //=> "number"
    console.log( +"10" === 10 )  //=> true;
    
    • 1
    • 2
    • 3
    • 4
    • 5

    8、检查无效

    在使用变量之前,我们经常需要检查其值是否为空。

    正常的方法是使用 if-else。

    function getUserRole(role) {
      let userRole;
    
      // If role is not falsy value
      // set `userRole` as passed `role` value
      if (role) {
        userRole = role;
      } else {
    
        // else set the `userRole` as USER
        userRole = 'USER';
      }
    
      return userRole;
    }
    
    console.log( getUserRole() )         //=> "USER"
    console.log( getUserRole('ADMIN') )  //=> "ADMIN";
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    使用 || 清理代码 :

    function getUserRole(role) {
      return role || 'USER';  // <-- here
    }
    
    console.log( getUserRole() )         //=> "USER"
    console.log( getUserRole('ADMIN') )  //=> "ADMIN";
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    9、字符串连接

    正常代码:

    let name = 'bytefish';
    let message = 'Hi '+ name + '!';;
    
    • 1
    • 2

    使用模板文字清洁代码:

    let name = 'bytefish';
    let message = `Hi ${name}!`;;
    
    • 1
    • 2

    10、使用速记

    正常代码:

    let x = 1
    
    if (x !== '' && x !== null && x !== undefined) {
      console.log('x is not nullish')
    };
    
    • 1
    • 2
    • 3
    • 4
    • 5

    使用速记运算符清洁代码:

    let x = 1
    
    if (!!x){
      console.log('x is not nullish')
    };
    
    • 1
    • 2
    • 3
    • 4
    • 5
  • 相关阅读:
    Java (JVM) 内存模型
    Minio分布式存储系统
    kCVPixelFormatType_32BGRA 格式的CMSampleBuffer sampebuffer 如何转化为 AVFrame
    空间金字塔池化Spatial Pyramid Pooling
    基于Redis手工实现分布式锁
    微信小程序获取微信用户步数
    HTML5期末大作业【红色的电影售票平台网站】web前端 html+css+javascript网页设计实例 企业网站制作
    zabbix监控nginx
    ChatGPT 提示词技巧一本速通
    Graph RAG: 知识图谱结合 LLM 的检索增强
  • 原文地址:https://blog.csdn.net/weixin_44161385/article/details/125515383