工作中经常使用的 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
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值