js常用的開發小技巧

1. 金錢格式化
    const formatNumber = str => str.replace(/\B(?=(\d{3})+(?!\d))/g, ',')
2. 取整
   let a = 3.12
   a = ~~a
3. 轉換數字字符串
   let a = '123'
   a = +a
4. 對象轉數組
   let obj = {name: 'tom', age: 23}
   let keys = Object.keys(obj)
   let values = Object.values(obj)
5. 數組去重
   const arr = [1, 2, 3, 1]
   arr = [...new Set(arr)]
6. 結構賦值
   const obj = {name: 'tom', age: 23}
   let {name, age} = obj
   const arr = ['tom', 23]
   let [name, age] = arr
7. 僞數組轉數組
   let bodys = document.getElementByTagName('body')
   Array.from(bodys)
   Array.prototype.slice.call(bodys)
8. 打亂數組
   let arr = [1, 2, 3, 4, 5, 6, 7, 'a', 'dsfs', 8, 9, 'v'];
   arr.sort(() => Math.random() - 0.5)
9. 隨機獲取數組中的元素
   const getRadomFromArr = arr => arr[Math.floor(Math.random()*arr.length)]
10. 強制取反
   let str = ''
   !!str


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章