前端小技巧:优雅的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;

 

 

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

posted @ 2021-09-23 10:23  smallbore  阅读(56)  评论(0编辑  收藏  举报
回顶部