ES6 给我们编程带来了很多便利,以前用大量代码实现的功能现在变得非常简洁。
本文总结了我在工作中经常使用的 7 个 JavaScript 技巧,希望对你也有帮助。
有时,我们需要找到数组中的最大值,你通常是怎么做的?
我们可以先对数组进行排序,然后,数组的最后一项就是最大值。
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
还有其他解决方案吗?是的,我们可以使用“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
如果有一个数字数组,得到它们总和的最快方法是什么?
const array = [ 1, 10, -19, 2, 7, 100 ]
const sum = array.reduce((sum, num) => sum + num) // 101
给你一个数组,现在你想从中获取一个随机值,你怎么做呢?
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
我们在抽奖的时候,需要打乱抽奖顺序。
const prizes = [ '', '', '', '' ]
prizes.sort(() => 0.5 - Math.random())
console.log(prizes) // ['', '', '', '']
prizes.sort(() => 0.5 - Math.random())
console.log(prizes) // ['', '', '', '']
现在我们有了一个多维嵌套数组,如何将其铺成一维数组?
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]
事实上,我们有一个更简单的方法来解决它。关于flat,我们来看看MDN的解释:
flat() 方法创建一个新数组,其中所有子数组元素递归连接到指定深度。
const array = [ 1, [ 2, [ 3, [ 4, [ 5 ] ] ] ] ]
console.log(array.flat(Infinity)) // [1, 2, 3, 4, 5]
过去,我们总是使用“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
你一定见过这样的判断方法,虽然,可以达到条件判断的目的,但是,看起来很繁琐。
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
}
网站题目:七个我在工作中经常使用的JavaScript技巧
网站URL:http://www.shufengxianlan.com/qtweb/news37/420487.html
网站建设、网络推广公司-创新互联,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等
声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联