iT邦幫忙

0

JS 陣列轉換&小技巧

Array.from 類陣列轉換

  • NodeList & HTMLCollection 類陣列轉換成陣列
    已寫另成一篇文 點我~
  • Array.from 用於陣列轉換
  • Array.from 亦可用來轉換 Set & Map
  • Set 可以用來去重
    const arr = [1, 2, 2, 3]
    const newArr = Array.from(new Set(arr))
    console.log(newArr) // [1, 2, 3]

字串 & 陣列轉換

  • 陣列轉換成字串 join(),若不傳值 會以 , 作為分割用
  • 字串轉陣列 split()
  • 字串轉陣列 Array.from()
    //  join() 陣列轉換成字串
    const strArr = ['A', 'B', 'C']
    
    let defaultStr = strArr.join()
    let spaceStr = strArr.join('')
    let str = strArr.join('、')
    
    console.log(defaultStr) // A,B,C
    console.log(spaceStr) // A B C
    console.log(str) // A、B、C
    
    // split() 字串轉陣列
    const str = '1 2 3 4 5 6'
    
    // ["1", "2", "3", "4", "5", "6"]
    console.log(str.split(' '))
    
    // Array.from() 字串轉陣列
    cosnt str = 'foo'
    console.log(Array.from(str)) // ["f", "o", "o"]

字串反轉

  • split() 將字串轉成陣列
  • reverse() 反轉陣列
  • join() 將陣列合併字串
    const str = 'Mom Get The Camera'
    const result = str.split('').reverse().join('')
    console.log(result)

產生一個範圍的數字陣列

丟個連結 此文寫的太好惹 推薦

數字陣列找最大最小值

  • ES6 rest parameter
    const numArr = [1, 2, 3, 4, 5]
    console.log('最大值', Math.max(...numArr))
    console.log('最小值', Math.min(...numArr))

實用小技巧

  • 使用length 作清空陣列 & 刪除末項,效能較pop佳
  • 利用length 判斷陣列是否為空
  • 利用length 加長陣列會以undefined填補空缺 (不佳別做!)
    // length
    let arr = [1, 2, 3]
    arr.length = 2
    console.log(arr) // [1, 2]
    arr.length = 0
    console.log(arr) // []
    
    const emptyArr = []
    console.log(emptyArr.length === 0) //true
    
    const arrPlus = [1, 2, 3]
    arrPlus.length = 5
     // [1, 2, 3, undefined, undefined]
     // GoogleChrome 顯示 empty !?
    console.log(arrPlus) 

參考資料

MDN
andyyou
Summer。桑莫。夏天
StackOverFlow產數字陣列


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言