• 前端小技巧:优雅的JavaScript编码


    JavaScript 编码技巧

    1. JavaScript 字符串数组转换

    const startArray = [1, 2, 3, 4, 5]
    const outputArray = startArray.map(String)
    console.log(outputArray) //  ["1", "2", "3", "4", "5"]
    数组map语法:array.map(function(currentValue,index,arr), thisValue)

    2. JavaScript 更容易的数组去重

    const startArray =[1, 2, 3, 3]
    const outputArray = [...new Set(startArray)]
    console.log(outputArray) // [1, 2, 3]

    3.JavaScript 找到数组中指定元素

    const startArray = [{id: 1, title: 'one'}, {id: 2, title: 'two'}]
    const outputItem = startArray.find(item => item.id === 2)
    console.log(outputItem) // {id: 2, title: 'two'}

     4. JavaScript 更简便的状态硬设

    // 数值
    function
    handleStatus(status) { const statusArray = ['black', 'red', 'blue', 'green', 'yellow']; return statusArray[status] || '默认'; } console.log(handleStatus(1)) // red

     // 字符串  
     function handleStatus(status) {
        const statusArray = {
          black: 'black',
          red: 'red',
          blue: 'blue',
          green: 'green',
          yellow: 'yellow'
        };
        return statusArray[status] || '默认';
      }

      5. JavaScript 优雅的对象获取

    const { test } = this.props;
    // 重命名
    const { test: mytest } = this.props;

    没有终点,没有彼岸,坚持就好,愿岁月如初

    smallbore,world
  • 相关阅读:
    LeetCode-Read N Characters Given Read4 II
    LeetCode-One Edit Distance
    LeetCode-Palindrome Permutation II
    LeetCode- Longest Absolute File Path
    LeetCode-Strobogrammatic Number II
    LeetCode-Strobogrammatic Number
    LeetCode-Flatten 2D Vector
    LeetCode-Shortest Word Distance III
    LeetCode-Shortest Word Distance II
    Cookie/Session
  • 原文地址:https://www.cnblogs.com/bore/p/15323049.html
Copyright © 2020-2023  润新知