分享ES6 20個經常使用技巧

前言:

ECMAScript 6(簡稱ES6)是於2015年6月正式發佈的JavaScript語言的標準,正式名為ECMAScript 2015(ES2015)。它的目標是使得JavaScript語言可以用來編寫復雜的大型應用程序,成為企業級開發語言  。

另外,一些情況下ES6也泛指ES2015及之後的新增特性,雖然之後的版本應當稱為ES7、ES8等

1.打亂數組順序

let arr = ['😄', 67, true, false, '55']
arr = arr.sort(() => 0.5 - Math.random())
console.log(arr)
// [ '😄', '55', 67, false, true ]

2.刪除數字之外的所有字符

const str = 'xieyezi 23213 is 95994 so hansome 223333'
const numbers = str.replace(/\D/g, '')
console.log(numbers)
// 2321395994223333

3.反轉字符串或者單詞

const sentence = 'xieyezi js so handsome, lol.'
const reverseSentence = reverseBySeparator(sentence, "")
console.log(reverseSentence);
// .lol ,emosdnah os sj izeyeix
const reverseEachWord = reverseBySeparator(reverseSentence, " ")
console.log(reverseEachWord)
// izeyeix sj os ,emosdnah .lol
function reverseBySeparator(string, separator) {
  return string.split(separator).reverse().join(separator)
}

4.將十進制轉換為二進制文件或十六進制數

const num = 45
num.toString(2)
num.tostring(16)

5.合並多個對象

const city = {
  name: 'Chongqing',
  population: '1,234,567,890'
}
const location = {
  longitude: '116.4',
  latitude: '39.9'
}
const fullCity = { ...city, ...location }
console.log(fullCity)
// {
//   name: 'Chongqing',
//   population: '1,234,567,890',
//   longitude: '116.4',
//   latitude: '39.9'
// }

6.=== 和 == 的區別

// ==   ->  類型轉換 (淺比較)
// ===  ->  無類型轉換 (嚴格比較)
0 == false // true
0 === false // false
1 == "1" // true
1 === "1" // false
null == undefined // true
null === undefined // false

7.解構賦值

const forest = {
  location: 'Sweden',
  animals: 3,
  animalsTypes: ['Lions', 'Tigers', 'Bears'],
};
const { location, animals, animalsTypes } = forest;
const [lions, tigers, bears] = animalsTypes;
console.log(location); // Sweden
console.log(animals); // 3
console.log(lions); // Lions
console.log(tigers); // Tigers
console.log(bears); // Bears

8.交換變量的值

let bears = 'bears'
let tigers = 'tigers'
[bears, tigers] = [tigers, bears]
console.log(bears) // tigers
console.log(tribes) // bears

9.字符串

9.1判斷回文字符串

const isRevervse = (str1, str2) => {
  const normalize = (str) =>
    str.toLowerCase()
    .normalize('NFD')
    .split('')
    .reverse()
    .join('')
  return normalize(str1) === str2
}
console.log(isRevervse('anagram', 'margana')) // true
console.log(isRevervse('rac', 'car')) // true

回文字符串: 正著寫和反著寫都一樣的字符串)

9.2判斷兩個字符串是否為互相排列

const isAnagram = (str1, str2) => {
  const normalize = (str) =>
    str.toLowerCase()
    .normalize('NFD')
    .split('')
    .sort()
    .join('')
  return normalize(str1) === normalize(str2)
}
console.log(isAnagram('anagram', 'nagaram')) // true
console.log(isAnagram('rat', 'car')) // false
console.log(isAnagram('heArT', 'traEH')) // true

判斷兩個字符串是否為互相排列: 給定兩個字符串,一個是否是另一個的排列

10.可選鏈操作符

const player = {
  name: 'xieyezi',
  rating: 1000,
  click: () => {
    return 'click'
  },
  pass: (teammate) => {
    return `Pass to ${teammate}`
  },
}
console.log(player?.name) // xieyezi
console.log(player?.click?.()) // click
console.log(player?.teammate?.()) // undefined

11.三目運算符

// condition ? expression if true : expression if false
const oxygen = 10
const diver = (oxygen < 10 ) ? 'Low oxygen' : 'High oxygen'
console.log(diver) // High oxygen

12.從數組中隨機選擇一個值

const elements = [24, 'You', 777, 'breaking', 99, 'full']
const random = (arr) => arr[Math.floor(Math.random() * arr.length)]
const randomElement = random(elements)
console.log(randomElement) // 777

13.凍結對象

const octopus = {
  tentacles: 8,
  color: 'blue',
}
Object.freeze(octopus)
octopus.tentacles = 10 // Error, 不會改變
console.log(octopus) // { tentacles: 8, color: 'blue'}

14.刪除數組重復的元素

const animals = ['bears', 'lions', 'tigers', 'bears', 'lions']
const unique = (arr) => [...new Set(arr)]

console.log(unique(animals)) // [ 'bears', 'lions', 'tigers' ]

15.保留指定位小數

const num = 0.123456789
const fixed2 = num.toFixed(2)
const fixed3 = num.toFixed(3)
console.log(fixed2) // 0.12
console.log(fixed3) // 0.123

16.清空數組

const numbers = [1, 2, 3, 4, 5]
numbers.length = 0
console.log(numbers) // []

17.從 RGB 轉換為 HEX

const rgbToHex = (r, g, b) => {
  const toHex = (num) => {
    const hex = num.toString(16)
    return hex.length === 1 ? `0${hex}` : hex
  }
  return `#${toHex(r)}${toHex(g)}${toHex(b)}`
}
console.log(rgbToHex(46, 32, 67)) // #2e2043

18.從數組中獲取最大值和最小值

const nums = [1, 2, 3, 4, 5, -3, 99, -45, -1]
const max = Math.max(...nums)
const min = Math.min(...nums)
console.log(max) // 99
console.log(min) // -45

19.空值合並運算符

const nullval = null
cost emptyString = ''
const someNum = 13
const a = nullval ?? 'A default'
const b = emptyString ?? 'B default'
const c = SomeNum ?? 'C default'
console.log(a) // A default
console.log(b) // '' // empty string != undefined or null
console.log(c) // 13

20.過濾數組中值為 false 的值

const nums = [1, 0 , undefined, null, false];
const truthyNums = nums.filter(Boolean);
console.log(truthyNums) // [1]

到此這篇關於分享ES6 20個經常使用技巧的文章就介紹到這瞭,更多相關ES6 技巧內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: