JavaScript 数组方法速查表(17 个必知方法)📄
熟记一些实用的数组方法可以提高你的问题解决能力。
所以我决定制作一份 JavaScript 数组方法速查表,这样我就可以快速复习数组方法,并始终牢记它们。
这份速查表包含了17种常用的数组方法:
toString()join()concat()splice()slice()indexOf()lastIndexOf()forEach()map()filter()reduce()some()every()flat()find()findIndex()sort()
视频
我还把这份速查表做成了视频。如果你觉得这个视频或速查表有用,可以订阅我的频道以示感谢🙏。
数组方法是共享的。
在 JavaScript 中,所有数组都由全局类构建Array。所有数组方法都存储在Array.prototype对象中。
这意味着数组方法通过原型继承在数组实例之间共享。
JavaScript 中的数组方法
Array.prototype.toString
将数组转换为以逗号分隔的数组值字符串:
let names = ["Zoe", "Adam", "Dan"]
let strNames = names.toString() // Zoe,Adam,Dan
Array.prototype.join
与此类似toString,但您可以指定分隔符:
let names = ["Zoe", "Adam", "Dan"]
let strNames = names.join(" and ") // Zoe and Adam and Dan
Array.prototype.concat
通过连接现有数组创建一个新数组:
let nums = [1, 2, 3]
let nums2 = [4, 5, 6]
let nums3 = [7, 8, 9]
let concatArr = nums.concat(nums2, nums3)
// [1, 2, 3, 4, 5, 6, 7, 8, 9]
数组.原型.拼接
该splice()方法可用于向数组中添加新元素:
let arr = ["Danny", "Joe"]
arr.splice(1, 0, "Alice", "Amy")
console.log(arr) // ['Danny', 'Alice', 'Amy', 'Joe']
第一个参数(1)定义了要添加(插入)新元素的索引。
第二个参数(0)定义了要删除多少个元素。
其余参数('Alice'、'Amy')定义了要添加的新元素。
splice()返回一个包含已删除项的数组:
let arr = ["Danny", "Joe"]
let spliced = arr.splice(1, 1, "Alice", "Amy") // ['Joe']
console.log(arr) // ['Danny', 'Alice', 'Amy']
我们也可以删除现有项目,而无需添加任何新项目:
let arr = ["Danny", "Joe", "Amy"]
let spliced = arr.splice(1, 1) // ['Joe']
console.log(arr) // ['Danny', 'Amy']
由于splice()会改变原始数组,因此最好在拼接之前先复制一份。
数组.原型.切片
slice()从数组中切出一部分,并将其存储在一个新数组中:
let arr = ["Danny", "Joe", "Amy"]
let slice = arr.slice(1) // ['Joe', 'Amy']
上面,我们从索引为 1 的元素开始切片,slice()不会改变原始数组。
我们可以提供起始索引和结束索引来进行拼接(直到但不包括结束索引):
let arr = ["Danny", "Joe", "Amy"]
let slice = arr.slice(0, 2) // ['Danny', 'Joe']
数组.原型.索引
查找包含特定值的第一个索引(从左到右搜索):
let arr = ["Danny", "Joe", "Amy", "Joe"]
let index = arr.indexOf("Joe") // 1
Array.prototype.lastIndexOf
查找包含特定值的最后一个索引(从右到左搜索):
let arr = ["Danny", "Joe", "Amy", "Joe"]
let index = arr.lastIndexOf("Joe") // 3
JavaScript 中的高阶数组方法
数组方法中,什么是高阶函数?
高阶函数是指接受函数作为参数,和/或返回函数的函数。因此,高阶函数是作用于其他函数的函数。
在 JavaScript 中,这些方法通过原型继承在数组实例之间共享Array.prototype。
Array.prototype.forEach
这种forEach方法本质上只是一种更简洁的写作方式for(let i = 0; i < arr.length; i++) {...}。
它遍历给定的数组,并对数组中的每个元素调用给定的回调函数。
传递给该函数的回调函数forEach()可以接受以下三个参数中的任意一个:
- 商品价值
- 项目索引
- 数组本身
例子:
let numbers = [1, 2, 3, 4]
numbers.forEach(n => console.log(n))
// 1
// 2
// 3
// 4
map如果你想返回一个包含每次回调运行返回值的新数组,那么最好使用这种方法。
数组.原型.映射
map 函数接收一个回调函数作为参数,并对当前数组的每个元素执行该回调函数。它将回调函数的每个返回值映射到一个新的数组中,而不会修改原始数组。
传递给该函数的回调函数map()可以接受以下三个参数中的任意一个:
- 商品价值
- 项目索引
- 数组本身
例如:
let numbers = [1, 2, 3, 4]
// Double all numbers
let doubledNumbers = numbers.map(n => n * 2) // [2, 4, 6, 8]
// Only double numbers at odd indexes
let doubledOddIndexNumbers = numbers.map((n, i) => {
if (i % 2 === 1) return n * 2
else return n
}) // [1, 4, 3, 8]
数组.原型.过滤器
filter 方法用于过滤掉数组中未通过布尔测试的元素。只有通过测试的元素才能进入新的返回数组。
传递给该函数的回调函数filter()可以接受以下三个参数中的任意一个:
- 商品价值
- 项目索引
- 数组本身
filter搜索栏就是一个很好的应用场景:
let articles = [
{ title: "PHP classes", author: "Danny Adams" },
{ title: "Python arrays", author: "Amy Sanders" },
{ title: "Arrays in PHP", author: "Danny Adams" },
]
// Lets say the user searches for all articles with PHP in the title
let PHPArticles = articles.filter(a => a.title.includes("PHP"))
// [
// { title: 'PHP classes', author: 'Danny Adams' },
// { title: 'Arrays in PHP', author: 'Danny Adams' },
// ];
另一个应用场景是按大小筛选:
let cities = [
{ name: "Stokington", rivers: 3 },
{ name: "Phillydelfia", rivers: 6 },
{ name: "New Ports", rivers: 2 },
]
let moreThanTwoRivers = cities.filter(c => c.rivers > 2)
// [
// { name: 'Stokington', rivers: 3 },
// { name: 'Phillydelfia', rivers: 6 },
// ];
Array.prototype.reduce
reduce 方法对数组中的每个元素运行回调函数,并将数组缩减为单个值。
reduce 函数本身接受两个参数:
- 回调函数
- 初始值
reduce(callback, initialVal)
传递给回调函数的reduce参数最多可以有四个:
- 总计或“累加器”
- 当前项目价值
- 当前项目索引
- 数组本身
例子:
let numbers = [1, 2, 3, 4]
let total = numbers.reduce((total, currentNum) => total + currentNum) // 10
在上面的例子中,total最初是数组中的第一个值(1),currentNum是第二个值(2)。
如果我们想从不同的值开始计算,可以传入第二个initialVal参数来调用 reduce 函数。假设我们想计算从 5 开始的总和:
let numbers = [1, 2, 3, 4]
let total = numbers.reduce((total, currentNum) => total + currentNum, 5) // 15
上面的数字total现在将从 5 开始,并且currentNum将成为数组中的第一个元素 (1)。
另一个不错的应用场景reduce是查找数组中的最大值或最小值:
let arr = [1, 2, 3]
let max = arr.reduce((a, b) => {
return Math.max(a, b)
}, -Infinity)
// 3
Array.prototype.some
该some方法检查数组中的某些值是否通过测试。它返回 truetrue或 false false。
回调函数接受 3 个参数:
- 商品价值
- 项目索引
- 数组本身
例子:
let numbers = [4, 6, 14, 16]
let isSomeGreaterThan6 = numbers.some(n => n > 6) // true
let isSomeLessThan4 = numbers.some(n => n < 4) // false
Array.prototype.every
every类似于该some方法,但它检查数组中的每个值是否通过某个测试,而不是只检查某些值。
例子:
let numbers = [4, 6, 14, 16]
let isEverythingGreaterThan6 = numbers.every(n => n > 6) // false
let isEverythingLessThan20 = numbers.some(n => n < 20) // true
数组.原型.扁平
该flat()方法创建一个新数组,将所有子数组元素递归地连接到该数组中,直到达到指定的深度。
例子:
let arr = [1, 2, 3, [1, 2], 4]
let flatArr = arr.flat() // [1, 2, 3, 1, 2, 4]
flat接受一个可选depth参数,depth用于指定嵌套数组结构应扁平化的深度,默认值为 1。
例子:
let arr = [1, 2, 3, [1, 2], [1, [1, 2]]]
let flatArr1 = arr.flat() // [1, 2, 3, 1, 2, 1, [1, 2]]
let flatArr2 = arr.flat(2) // [1, 2, 3, 1, 2, 1, 1, 2]
Array.prototype.find
该find方法返回数组中第一个通过特定测试的元素。
传递给回调函数的find参数有 3 个:
- 商品价值
- 项目索引
- 数组本身
例子
let stock = [
{ item: "ketchup", quantity: 32 },
{ item: "mayo", quantity: 9 },
{ item: "hot sauce", quantity: 12 },
]
let mayo = stock.find(s => s.item === "mayo")
// { item: 'mayo', quantity: 9 }
Array.prototype.findIndex
与此相同find,但返回索引而不是值:
let stock = [
{ item: "ketchup", quantity: 32 },
{ item: "mayo", quantity: 9 },
{ item: "hot sauce", quantity: 12 },
]
let mayoIndex = stock.findIndex(s => s.item === "mayo")
// 1
数组.原型.排序
sort将数组元素按升序排列。它是一种“原地”排序算法——这意味着它会改变原始数组并返回结果。
默认情况下,sort适用于字符串:
let names = ["Zoe", "Adam", "Dan"]
names.sort()
console.log(names) // ['Adam', 'Dan', 'Zoe']
对于数字,我们需要传递一个比较回调函数:
let numbers = [3, 1, 7, 2]
numbers.sort((a, b) => a - b)
console.log(numbers) // [1, 2, 3, 7]
初始时,a为 3,b为 1。如果a - b为负数,则知道b大于,因此应该在之后a。如果为正数,b则应该在之前a。
感谢阅读!
想了解更多我的信息,您可以:
- 请在推特上关注我。
- 请订阅我的YouTube频道,我计划在不久的将来发布更多编程视频。
干杯!
文章来源:https://dev.to/doabledanny/javascript-array-method-cheat-sheet-17-must-know-methods-441g