JAVAScript高級進階課程中ES6內容 給我們編程帶來了很多便利,以前用大量代碼實現的功能現在變得非常簡潔,總結了工作中經常使用的 5個 JavaScript 技巧,希望對你也有幫助。
(1)、找出數組中的最大值或最小值
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)、展平多層數組
解決方法 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
const array = [ 1, [ 2, [ 3, [ 4, [ 5 ] ] ] ] ]
console.log(array.flat(Infinity)) // [1, 2, 3, 4, 5]
(4)、檢查數組是否包含值
當我們遇到對象數組時判斷數據是否符合預期可以使用ES6 findIndex 方法
const array = [
{ name: '張無忌' },
{ name: '趙敏' },
{ name: '高圓圓' }
]
const index = array.findIndex((it) => it.name === '張無忌')
// 0
(5)、使用“includes”方法進行判斷
你一定見過這樣的判斷方法,雖然,可以達到條件判斷的目的,但是不怎么優雅。
const value = '0'
if (value === '0' || value === '1' || value === '2') {
console.log('hello 源碼')
// hello 源碼
}
includes方法讓代碼更簡單甚至更可擴展
const man = '0'
const woman = '1'
const unknow = '2'
const conditions = [ man , woman , unknow ]
const value = '0'
if (conditions.includes(value)) {
console.log('hello源碼')
// hello 源碼
}






