JS数组奇巧淫技

用很差数组的程序猿不是一个好猿,我说的~html

前段时间接手一个项目,逻辑晦涩难懂,代码庞大冗余,上手极其困难。很大的缘由就是数组方法使用不熟练,致使写出了不少垃圾代码,其实不少地方稍加改动就能够变得简单高效又优雅。所以我在这里总结下数组的经常使用方法和奇巧淫技(奇巧淫技主要是reduce~)。es6

数组操做首先要注意且牢记splice、sort、reverse这3个经常使用方法是对数组自身的操做,会改变数组自身。其余会改变自身的方法是增删push/pop/unshift/shift、填充fill和复制填充copyWithin后端

先说数组经常使用方法,后说使用误区。数组

数组经常使用方法

先献上数组方法懒人图一张祭天 (除了Array.keys()/Array.values()/Array.entries()基本都有):安全

数组方法大全

生成相似[1-100]这样的的数组:

测试大量数据的数组时能够这样生成:数据结构

// fill
const arr = new Array(100).fill(0).map((item, index) => index + 1)

// Array.from() 评论区大佬指出
const arr = Array.from(Array(100), (v, k) => k + 1)

// Array.from() + array.keys() 评论区大佬指出
const ary = [...Array(100).keys()] 
复制代码

new Array(100) 会生成一个有100空位的数组,这个数组是不能被map(),forEach(), filter(), reduce(), every() ,some()遍历的,由于空位会被跳过(for of不会跳过空位,能够遍历)。 [...new Array(4)] 能够给空位设置默认值undefined,从而使数组能够被以上方法遍历。函数

数组解构赋值应用

// 交换变量
[a, b] = [b, a]
[o.a, o.b] = [o.b, o.a]
// 生成剩余数组
const [a, ...rest] = [...'asdf'] // a:'a',rest: ["s", "d", "f"]
复制代码

数组浅拷贝

const arr = [1, 2, 3]
const arrClone = [...arr]
// 对象也能够这样浅拷贝
const obj = { a: 1 }
const objClone = { ...obj }
复制代码

浅拷贝方法有不少如arr.slice(0, arr.length)/Arror.from(arr)等,可是用了...操做符以后就不会再想用其余的了~post

数组合并

const arr1 = [1, 2, 3]
const arr2 = [4, 5, 6]
const arr3 = [7, 8, 9]
const arr = [...arr1, ...arr2, ...arr3]
复制代码

arr1.concat(arr2, arr3)一样能够实现合并,可是用了...操做符以后就不会再想用其余的了~测试

数组去重

const arr = [1, 1, 2, 2, 3, 4, 5, 5]
const newArr = [...new Set(arr)]
复制代码

new Set(arr)接受一个数组参数并生成一个set结构的数据类型。set数据类型的元素不会重复且是Array Iterator,因此能够利用这个特性来去重。ui

数组取交集

const a = [0, 1, 2, 3, 4, 5]
const b = [3, 4, 5, 6, 7, 8]
const duplicatedValues = [...new Set(a)].filter(item => b.includes(item))
duplicatedValues // [3, 4, 5]
复制代码

数组取差集

const a = [0, 1, 2, 3, 4, 5]
const b = [3, 4, 5, 6, 7, 8]
const diffValues = [...new Set([...a, ...b])].filter(item => !b.includes(item) || !a.includes(item)) // [0, 1, 2, 6, 7, 8]
复制代码

数组转对象

const arr = [1, 2, 3, 4]
const newObj = {...arr} // {0: 1, 1: 2, 2: 3, 3: 4}
const obj = {0: 0, 1: 1, 2: 2, length 3}
// 对象转数组不能用展开操做符,由于展开操做符必须用在可迭代对象上
let newArr = [...obj] // Uncaught TypeError: object is not iterable...
// 可使用Array.form()将类数组对象转为数组
let newArr = Array.from(obj) // [0, 1, 2]
复制代码

数组摊平

const obj = {a: '群主', b: '男群友', c: '女裙友', d: '未知性别'}
const getName = function (item) { return item.includes('群')}
// 方法1
const flatArr = Object.values(obj).flat().filter(item => getName(item))
// 经大佬指点,更加简化(发现本身的抽象能力真的差~)
const flatArr = Object.values(obj).flat().filter(getName)
复制代码

二维数组用array.flat(),三维及以上用array.flatMap()

数组经常使用遍历

数组经常使用遍历有 forEach、every、some、filter、map、reduce、reduceRight、find、findIndex 等方法,不少方法均可以达到一样的效果。数组方法不只要会用,并且要用好。要用好就要知道何时用什么方法。

遍历的混合使用

filtermap方法返回值仍旧是一个数组,因此能够搭配其余数组遍历方法混合使用。注意遍历越多效率越低~

const arr = [1, 2, 3, 4, 5]
const value = arr
    .map(item => item * 3)
    .filter(item => item % 2 === 0)
    .map(item => item + 1)
    .reduce((prev, curr) => prev + curr, 0)
复制代码

检测数组全部元素是否都符合判断条件

const arr = [1, 2, 3, 4, 5]
const isAllNum = arr.every(item => typeof item === 'number')
复制代码

检测数组是否有元素符合判断条件

const arr = [1, 2, 3, 4, 5]
const hasNum = arr.some(item => typeof item === 'number')
复制代码

找到第一个符合条件的元素/下标

const arr = [1, 2, 3, 4, 5]
const findItem = arr.find(item => item === 3) // 返回子项
const findIndex = arr.findIndex(item => item === 3) // 返回子项的下标

// 我之后不再想看见下面这样的代码了😂
let findIndex
arr.find((item, index) => {
    if (item === 3) {
        findIndex = index
    }
})
复制代码

数组使用误区

数组的方法不少,不少方法均可以达到一样的效果,因此在使用时要根据需求使用合适的方法。

垃圾代码产生的很大缘由就是数组经常使用方法使用不当,这里有如下须要注意的点:

array.includes() 和 array.indexOf()

array.includes() 返回布尔值,array.indexOf() 返回数组子项的索引。indexOf 必定要在须要索引值的状况下使用。

const arr = [1, 2, 3, 4, 5]

// 使用indexOf,须要用到索引值
const index = arr.indexOf(1) // 0
if (~index) { // 若index === -1,~index获得0,判断不成立;若index不为-1,则~index获得非0,判断成立。
    arr.spilce(index, 1)
}

// 使用includes,不须要用到索引值
// 此时若用indexOf会形成上下文上的阅读负担:到底其余地方有没有用到这个index?
const isExist = arr.includes(6) // true
if (!isExist) {
    arr.push(6)
}
复制代码

array.find() 、 array.findIndex() 和 array.some()

array.find()返回值是第一个符合条件的数组子项,array.findIndex() 返回第一个符合条件的数组子项的下标,array.some() 返回有无复合条件的子项,若有返回true,若无返回false。注意这三个都是短路操做,即找到符合条件的以后就不在继续遍历。

在须要数组的子项的时候使用array.find() ;须要子项的索引值的时候使用 array.findIndex() ;而若只须要知道有无符合条件的子项,则用 array.some()

const arr = [{label: '男', value: 0}, {label: '女', value: 1}, {label: '不男不女', value: 2}]

// 使用some
const isExist = arr.some(item => item.value === 2)
if (isExist) {
    console.log('哈哈哈找到了')
}

// 使用find
const item = arr.find(item => item.value === 2)
if (item) {
    console.log(item.label)
}

// 使用findIndex
const index = arr.findIndex(item => item.value === 2)
if (~index) {
    const delItem = arr[index]
    arr.splice(index, 1)
    console.log(`你删除了${delItem.label}`)
}
复制代码

建议在只须要布尔值的时候和数组子项是字符串或数字的时候使用 array.some()

// 当子包含数字0的时候可能出错
const arr = [0, 1, 2, 3, 4]

// 正确
const isExist = arr.some(item => item === 0)
if (isExist) {
    console.log('存在要找的子项,很舒服~')
}

// 错误
const isExist = arr.find(item => item === 0)
if (isExist) { // isExist此时是0,隐式转换为布尔值后是false
    console.log('执行不到这里~')
}


// 当子项包含空字符串的时候也可能出错
const arr = ['', 'asdf', 'qwer', '...']

// 正确
const isExist = arr.some(item => item === '')
if (isExist) {
    console.log('存在要找的子项,很舒服~')
}

// 错误
const isExist = arr.find(item => item === '')
if (isExist) { // isExist此时是'',隐式转换为布尔值后是false
    console.log('执行不到这里~')
}
复制代码

array.find() 和 array.filter()

只须要知道 array.filter() 返回的是全部符合条件的子项组成的数组,会遍历全部数组;而 array.find() 只返回第一个符合条件的子项,是短路操做。再也不举例~

合理使用 Set 数据结构

因为 es6 原生提供了 Set 数据结构,而 Set 能够保证子项不重复,且和数组转换十分方便,因此在一些可能会涉及重复添加的场景下能够直接使用 Set 代替 Array,避免了多个地方重复判断是否已经存在该子项。

const set = new Set()
set.add(1)
set.add(1)
set.add(1)
set.size // 1
const arr = [...set] // arr: [1]
复制代码

强大的reduce(奇巧淫技)

array.reduce 遍历并将当前次回调函数的返回值做为下一次回调函数执行的第一个参数。

利用 array.reduce 替代一些须要屡次遍历的场景,能够极大提升代码运行效率。

  1. 利用reduce 输出一个数字/字符串

假若有以下每一个元素都由字母's'加数字组成的数组arr,如今找出其中最大的数字:(arr不为空)

const arr = ['s0', 's4', 's1', 's2', 's8', 's3']

// 方法1 进行了屡次遍历,低效
const newArr = arr.map(item => item.substring(1)).map(item => Number(item))
const maxS = Math.max(...newArr)

// 方法2 一次遍历
const maxS = arr.reduce((prev, cur) => {
  const curIndex = Number(cur.replace('s', ''))
  return curIndex > prev ? curIndex : prev
}, 0)
复制代码
  1. 利用reduce 输出一个数组/对象
const arr = [1, 2, 3, 4, 5]

 // 方法1 遍历了两次,效率低
const value = arr.filter(item => item % 2 === 0).map(item => ({ value: item }))

// 方法1 一次遍历,效率高
const value = arr.reduce((prev, curr) => {
    return curr % 2 === 0 ? [...prev, curr] : prev
}, [])
复制代码

掌握了上面两种用法,结合实际须要,就能够用 reduce/reduceRight 实现各类奇巧淫技了。

实例:利用 reduce 作下面这样的处理来生成想要的 html 字符串:

// 后端返回数据
const data = {
  'if _ then s9': [
    '做用属于各类,结构属于住宅,结构能承受做用,做用属于在正常建造和正常使用过程当中可能发生',
    '做用属于各类,结构属于住宅,结构能承受做用,做用属于在正常建造和正常使用过程当中可能发生',
    '做用属于各类,结构属于住宅,结构能承受做用,做用属于在正常建造和正常使用过程当中可能发生'
    ],
  'if C then s4': [
    '当有条件时时,结构构件知足要求,要求属于安全性、适用性和耐久性',
    '当有条件时时,住宅结构知足要求,要求属于安全性、适用性和耐久性'
  ]
}

const ifthens = Object.entries(data).reduce((prev, cur) => {
  const values = cur[1].reduce((prev, cur) => `${prev}<p>${cur}</p>`, '')
  return ` ${prev} <li> <p>${cur[0]}</p> ${values} </li> `
}, '')

const html = ` <ul class="nlp-notify-body"> ${ifthens} </ul> `
复制代码

生成的 html 结构以下:

<ul class="nlp-notify-body">            
  <li>
    <p>if _ then s9</p>
    <p>做用属于各类,结构属于住宅,结构能承受做用,做用属于在正常建造和正常使用过程当中可能发生</p>
    <p>做用属于各类,结构属于住宅,结构能承受做用,做用属于在正常建造和正常使用过程当中可能发生</p>
    <p>做用属于各类,结构属于住宅,结构能承受做用,做用属于在正常建造和正常使用过程当中可能发生</p>
  </li>
  <li>
    <p>if C then s4</p>
    <p>当有条件时时,结构构件知足要求,要求属于安全性、适用性和耐久性</p>
    <p>当有条件时时,住宅结构知足要求,要求属于安全性、适用性和耐久性</p>
  </li>
</ul>
复制代码

这里还有一个替代 reverse 函数的技巧

因为 array.reverse() 函数会改变原数组自身,这样就限制了一些使用场景。若是我想要一个不会改变数组自身的 reverse 函数呢?拿走!

const myReverse = (arr = []) => {
    return  arr.reduceRight((prev, cur) => [...prev, cur], []) // 也能够返回逗号表达式 (prev.push(cur), prev)
}
复制代码

reduce 太强大了,这里只能展现基本用法。到底有多强大推荐查看大佬这篇《25个你不得不知道的数组reduce高级用法》

大招

哎,流年不利,情场失意。程序界广大朋友中单身的很多,这是我从失败中总结出的一点经验教训,请笑纳😂~

相关文章
相关标签/搜索
本站公众号
   欢迎关注本站公众号,获取更多信息