英文 | https://javascript.plainenglish.io/7-es6-javascript-tricks-to-make-you-a-better-programmer-a3edd07c1f52
前言
ES6 給我們程式設計帶來了很多便利,以前用大量代碼實作的功能現在變得非常簡潔。
本文總結了我在工作中經常使用的 7 個 JavaScript 技巧,希望對你也有幫助。
1. 找出數組中的最大值或最小值
有時,我們需要找到數組中的最大值,你通常是怎麼做的?
解決方案 1
我們可以先對數組進行排序,然後,數組的最後一項就是最大值。
const array = [ 1, 10, -19, 2, 7, 100 ]
array.sort((a, b) => a - b)
console.log('max value', array[ array.length - 1 ]) // 100
console.log('min value', array[ 0 ]) // -19
解決方案 2
還有其他解決方案嗎?是的,我們可以使用“Math.max”輕松處理它。
const array = [ 1, 10, -19, 2, 7, 100 ]
console.log('max value', Math.max(...array)) // 100
console.log('min value', Math.min(...array)) // -19
2.計算數組的總和
如果有一個數字數組,得到它們總和的最快方法是什麼?
const array = [ 1, 10, -19, 2, 7, 100 ]
const sum = array.reduce((sum, num) => sum + num) // 101
3. 從數組中擷取随機值
給你一個數組,現在你想從中擷取一個随機值,你怎麼做呢?
const array = [ 'fatfish', 'fish', 24, 'hello', 'world' ]
const getRandomValue = (array) => {
return array[ Math.floor(Math.random() * array.length) ]
}
console.log(getRandomValue()) // world
console.log(getRandomValue()) // world
console.log(getRandomValue()) // 24
4.随機打亂數組的值
我們在抽獎的時候,需要打亂抽獎順序。
const prizes = [ '📱', '🍫', '🍵', '🍔' ]
prizes.sort(() => 0.5 - Math.random())
console.log(prizes) // ['📱', '🍔', '🍫', '🍵']
prizes.sort(() => 0.5 - Math.random())
console.log(prizes) // ['🍫', '🍔', '📱', '🍵']
5. 展平多層陣列
現在我們有了一個多元嵌套數組,如何将其鋪成一維數組?
解決方案 1
const array = [ 1, [ 2, [ 3, [ 4, [ 5 ] ] ] ] ]
const flattenArray = (array) => {
return array.reduce((res, it) => {
return res.concat(Array.isArray(it) ? flattenArray(it) : it)
}, [])
}
console.log(flattenArray(array)) // [1, 2, 3, 4, 5]
解決方案 2
事實上,我們有一個更簡單的方法來解決它。關于flat,我們來看看MDN的解釋:
flat() 方法建立一個新數組,其中所有子數組元素遞歸連接配接到指定深度。
const array = [ 1, [ 2, [ 3, [ 4, [ 5 ] ] ] ] ]
console.log(array.flat(Infinity)) // [1, 2, 3, 4, 5]
6.檢查數組是否包含值
過去,我們總是使用“indexOf”方法來檢查數組是否包含值。如果“indexOf”傳回的值大于-1,則表示有一個。
const array = [ 'fatfish', 'hello', 'world', 24 ]
console.log(array.indexOf('fatfish')) // 0
console.log(array.indexOf('medium')) // -1
但是,現在資料比較複雜,我們将無法通過 indexOf 方法直接确認數組中是否存在“fatfish”。幸運的是,ES6 中提供了 findIndex 方法。
const array = [
{
name: 'fatfish'
},
{
name: 'hello'
},
{
name: 'world'
},
]
const index = array.findIndex((it) => it.name === 'fatfish') // 0
7.使用“includes”方法進行判斷
你一定見過這樣的判斷方法,雖然,可以達到條件判斷的目的,但是,看起來很繁瑣。
const value = 'fatfish'
if (value === 'fatfish' || value === 'medium' || value === 'fe') {
console.log('hello world') // hello world
}
我們可以使用includes方法讓代碼更簡單甚至更可擴充
const conditions = [ 'fatfish', 'medium', 'fe' ]
const value = 'fatfish'
if (conditions.includes(value)) {
console.log('hello world') // hello world
}
最後
以上就是我今天跟你分享的7個我在工作中經常使用的ES6技巧,希望這些技巧也能夠幫助到你,如果你覺有用有幫助的話,請記得點贊我,關注我,并與你的朋友分享這篇文章,最後,感謝你的閱讀。