发布于 2025-12-07 0 阅读
0

数组速查表

数组速查表

几天前,我偶然看到了 Emma Bostian 的一篇非常好的帖子,一个RegExp Cheatsheet。

当时那篇文章看起来非常有用,启发了我去做一些类似的事情。所以我选择了数组。以下是一些精选的方法,我相信如果你掌握了它们,你将会成为一个更高效的 JavaScript 开发者。

目录

  1. 平坦的
  2. 平面地图
  3. 每一个
  4. 一些
  5. 减少右
  6. 取消移位
  7. 片
  8. 种类
  9. 从
  10. 复制
  11. lastIndexOf
  12. 寻找
  13. 查找索引
  14. 打破循环

平坦的

减少阵列中的层数

const bigArray = [[22], [33, 55, [23, 11], 50], 100, 109]

const oneLess = bigArray.flat()
// [22, 33, 55, [23, 11], 50, 100, 109]

const allGone = bigArray.flat(Infinity)
// [22, 33, 55, 23, 11, 50, 100, 109]
Enter fullscreen mode Exit fullscreen mode

它接受一个参数depth: number,指定要移除的层数。默认值为1。

Array.flat()⚡️不到一分钟就查看此视频!

平面地图

正相反,顾名思义,flatMap()就是与相同map().flat(1),而不是相反。

🚨 注意1到flat().
flatMap 总是以depth1 运行。

因为flatMap删除了空数组,所以输出数组不需要length与原始数组相同。

const mutants = ['Wolverine', 'Storm', 'Jubilee', 'Cyclops']

// React-like environment. JSX 👇
const App = () => (
  <div>
    {mutants.flatMap((mutant, index) => [
      ...(index > 0 ? [', '] : []),
      <span>{mutant}</span>,
    ])}
  </div>
)

// Wolverine, Storm, Jubilee, Cyclops

Enter fullscreen mode Exit fullscreen mode

Array.flatMap()⚡️不到一分钟就查看此视频!

每一个

接收回调的方式与更流行的 完全相同map。filter但是,如果迭代中的每个项目都符合回调中的条件,.every()则会输出一个声明。booleanarray

const menu = {
    type: '🍔',
    quantity: 'big',
  },
  {
    type: '🍕',
    quantity: 'big',
  },
  {
    type: '🍜',
    quantity: 'medium',
  },
]

const hasOnlyBigMeals = menu.every(({ quantity }) => quantity === 'big')

// false (🍜 is 'medium')

Enter fullscreen mode Exit fullscreen mode

一些

map接收回调的方式与更流行的filter(以及上面的 )完全相同every。与 一样every,它会boolean在回调中输出一个描述匹配条件的 。但是,如果中至少有一个项目符合条件,some则返回。truearray

const menu = {
    type: '🍔',
    price: 10.9,
  },
  {
    type: '🍕',
    price: 3.9,
  },
  {
    type: '🍜',
    price: 8.9,
  },
]

const hasPricey = menu.some(({ price }) => price > 10)

// true (🍔 is above 10)
Enter fullscreen mode Exit fullscreen mode

⚡️ 想了解更多关于检查数组内容的信息吗?观看这个关于some、every和 的简短视频includes!

减少右

这个.reduce()和更流行的那个完全一样,唯一的区别是它的运行方式是相反的。Reduce-RIGHT。明白了吗?😅

const dogs = [
  'corgi',
  'beagle',
  'schnauzer'
]

dogs.reduceRight((acc, item, index, arr) => {
  return `${acc} ${item}${index === 0 ? ' 🦴' : ', '}`
}, '')

// schnauzer,  beagle,  corgi 🦴
Enter fullscreen mode Exit fullscreen mode

取消移位

将元素添加到 的开头array。

const xmen = ['Cyclops', 'Jean Grey', 'Storm', 'Beast']
xmen.unshift('Wolverine')

// ['Wolverine', 'Cyclops', 'Jean Grey', 'Storm', 'Beast']

Enter fullscreen mode Exit fullscreen mode

片

返回从(默认为第一个元素)到(默认为最后一个元素)的浅表副本。arraystartend

const xmen = [
  'Jubilee',
  'Kitty Pride',
  'Storm'
]

xmen.slice(0,2)
// ['Jubilee', 'Kitty Pride']

Enter fullscreen mode Exit fullscreen mode

❗专业提示:
在函数式编程范式中使用可变方法非常有用

种类

按特定顺序排列数组中的项目。默认为升序。它接受一个比较函数callback,第一个和第二个元素分别是参数。

🚨 小心!
元素将被强制转换为string

let numbers = [8, 1, 11, 4]

numbers.sort()
//['1', '11', '4', '8']

let numbersAgain = [8, 1, 11, 4]

numbersAgain.sort((a, b) => a - b)
// [1, 4, 8, 11]

numbersAgain.sort((a, b) => b - a)
// [11, 8, 4, 1]
Enter fullscreen mode Exit fullscreen mode

如果比较函数返回

  • 小于 0:a在之前b
  • 0:一切保持原样
  • 大于 0:a追随b

从

从类数组或可迭代对象创建一个新的、浅复制的数组实例。

const object = {
  0: 'a'
  1: 'b'
  2: 'c'
  length: 3 // it needs to have length prop here
}

Array.from(object)

// ['a', 'b', 'c']
Enter fullscreen mode Exit fullscreen mode

复制

将部分内容复制到同一array数组内的另一个位置,而不改变其长度。

const array = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']

array.copyWithin(1,4,7)
// ['a', 'e', 'f','g', 'e', 'f', 'g', 'h']

Enter fullscreen mode Exit fullscreen mode

复制到从索引到的位置1元素。47

lastIndexOf

返回 中某个项目的最后一个可能索引array。

const xmen = ['J.Madrox', 'Jubilee', 'J.Madrox', 'Wolverine', 'J.Madrox']

xmen.lastIndexOf('J.Madrox')
// 4

Enter fullscreen mode Exit fullscreen mode

寻找

扫描array并返回第一个满足回调的元素。


const number = [55, 65, 39, 44]
const multiple3 = number.find(item => item % 3 === 0)
// 39

Enter fullscreen mode Exit fullscreen mode

查找索引

扫描array并返回index第一个满足回调的元素。


const number = [55, 65, 39, 44]
const multiple3 = number.findIndex(item => item % 3 === 0)
// 2

Enter fullscreen mode Exit fullscreen mode

跳出循环

停止循环并非易事。为了做到这一点,你需要改变循环所针对的数组,但在处理不可变数据时,你肯定不希望这样做(例如使用函数式方法:map、reduce、filter、flat、flatMap 等)。

还记得slice吗?Slice 返回传入元素的子数组。我们在开始之前就做了这件事,这意味着循环是在 的浅拷贝上运行的array。

要突破这一点,只需使用.splice()。Splice 会删除或
替换 中的元素array。

const bigArray = new Array(100).fill(1)

const contentSum = bigArray
  .slice(0)
  .reduce((acc, item, index, array) => {
    if (index === 10) {
      array.splice(0)
    }

    console.log(index)
    return index
  }, 0)

// 10
Enter fullscreen mode Exit fullscreen mode

这个列表里还包含哪些方法?有没有你之前从未遇到过的方法?请在评论区留言告诉我!

另外,希望你觉得这篇文章有用。如果觉得有用,请考虑分享到你的人脉圈,这对我来说意义重大!如果你对这篇文章或其他文章有任何反馈,欢迎在评论区或推特上留言!

鏂囩珷鏉ユ簮锛�https://dev.to/atila/array-cheatsheet-4me0