用这些技巧提高你的 JS 技能 #1
在本文中,我将与您分享一些有关 JS 的技巧,这些技巧可以提高您的 JS 技能!
包括避免重复检查的方法
您可以轻松地替换它
if (value === 'a' || value === 'b' || value === 'c') { ... }
经过
if (['a', 'b', 'c'].includes(value)) { ... }
更清洁,避免你的if
双!
运算符将任何变量转换为布尔值
可以使用 (NOT) 运算符!
两次!!
以将任何变量转换为布尔值(如布尔函数),当您需要在处理某些值之前检查它时非常方便。
const toto = null
!!toto // false
Boolean(toto) // false
if (!!toto) { } // toto is not null or undefined
可选链式调用
在处理对象之前,你javascript
需要经常检查它的某些属性是否存在。很多开发者使用这种方法:
const toto = { a: { b: { c: 5 } } }
if (!!toto.a && !!toto.a.b && !!toto.a.b.c) { ... } // toto.a.b.c exist
您可以使用optional chaining
以避免使用像上面那样的多重检查器。
const toto = { a: { b: { c: 5 } } }
if (!!toto.a?.b?.c) { ... } // toto.a.b.c exist
// If the key doesn't exist, it will return undefined
const test = toto.a?.b?.c?.d // undefined
在 if 语句中返回值时避免使用 Else
我已经多次看到过这种情况:
if (...) { // the condition is not important in this example
return 'toto'
} else {
return 'tutu'
}
如果您的 if 返回值,您只需将上面的代码替换为:
if (...) { // the condition is not important in this example
return 'toto'
}
return 'tutu'
如果您需要使用 else if,那么您可以,但是您需要为每个 else if 返回一个值!
避免使用 ForEach,更多地使用 Filter、Map、Reduce、Every 和 Some 函数
我从这篇文章中得到的最好的建议是,作为初学者,我们使用了很多 forEach 函数,但 JS 为您提供了很多替代方案,而且这些函数是 FP(函数式编程)。
这些功能是什么?使用的时候我会解释给你听!
筛选
顾名思义,它允许我们根据您的条件过滤数组中的某些值。
const toto = [1, 2, 3, 4]
const evenValue = toto.filter(currentValue => {
return currentValue % 2 == 0 // remove all value that return false with this condition
}) // [2, 4]
地图
当你需要将项目中的所有项目转换为另一个项目时,请使用 map,例如,如果你想转换所有数字并将它们乘以 2
const toto = [1, 2, 3, 4]
const valueMultiplied = toto.map(currentValue => {
return currentValue * 2 // remove all value that return false with this condition
}) // [2, 4, 6, 8]
减少
最难理解的是,与其他函数不同,reduce 还有另一个东西,accumulator
这个是什么,什么时候使用它?
了解是否需要使用以下好规则reduce
:
Do you need to get a single value from your array ?
例如,如果我想将数组中的所有数字加起来为一个值,你就需要 ,reduce
并且accumulator
就是总和!和任何值一样,你需要初始化它!
const toto = [1, 2, 3, 4]
const sum = toto.reduce((accumulator, currentValue) => {
return accumulator += currentValue // you always need to return the accumulator
}, 0) // 10
一些和每一个
我最喜欢的之一,虽然我不是每天都用,但我喜欢它!
some
将检查您的所有物品,当其中一个物品符合要求时match your condition
,它将返回true
,否则它将返回false
。
every
将检查您的所有物品,当其中一个物品符合要求时don't match your condition
,它将返回false
,否则它将返回true
。
但什么时候使用它?
例如,如果您需要确保所有物品都符合某个条件!
const toto = [ 2, 4 ]
if (toto.every(val => val % 2 === 0)) { } // You are sure that your array contains only even value
const falsyToto = [ 2, 4, 5 ]
falsyToto.every(val => val % 2 === 0) // return false since array contain a odd value !
您可以在相反的上下文中使用some
,例如,如果您想确保数组包含at least
一个奇数值
const toto = [ 2, 4, 5 ]
toto.some(val => val % 2 !== 0) // return true
我希望你喜欢这篇文章!
🎁 如果您在TwitterUnderrated skills in javascript, make the difference
上关注我并给我点赞,即可免费获得我的新书😁
或者在这里获取
☕️ 你可以支持我的作品🙏
🏃♂️ 你可以关注我 👇
🕊 推特:https://twitter.com/code__oz
👨💻 Github:https://github.com/Code-Oz
你也可以标记🔖这篇文章!
文章来源:https://dev.to/codeoz/improve-your-js-skills-with-theses-tips-52ia