【JavaScript】34_数组常用方法

时间:2022-05-04 00:42:15

18、数组的方法

sort()

  • sort用来对数组进行排序(会对改变原数组)
  • sort默认会将数组升序排列 注意:sort默认会按照Unicode编码进行排序,所以如果直接通过sort对数字进行排序 可能会得到一个不正确的结果
  • 参数:
  • 可以传递一个回调函数作为参数,通过回调函数来指定排序规则 (a, b) => a - b 升序排列 (a, b) => b - a 降序排列

forEach()

  • 用来遍历数组
  • 它需要一个回调函数作为参数,这个回调函数会被调用多次 数组中有几个元素,回调函数就会调用几次 每次调用,都会将数组中的数据作为参数传递
  • 回调函数中有三个参数: element 当前的元素 index 当前元素的索引 array 被遍历的数组

filter()

  • 将数组中符合条件的元素保存到一个新数组中返回
  • 需要一个回调函数作为参数,会为每一个元素去调用回调函数,并根据返回值来决定是否将元素添加到新数组中
  • 非破坏性方法,不会影响原数组

map()

  • 根据当前数组生成一个新数组
  • 需要一个回调函数作为参数, 回调函数的返回值会成为新数组中的元素
  • 非破坏性方法,不会影响原数组

reduce()

  • 可以用来将一个数组中的所有元素整合为一个值(累计值,可为累加,累乘之类的)
  • 参数:
  1. 回调函数,通过回调函数来指定合并的规则
  2. 可选参数,初始值
<script>
let arr = ["a", "c", "e", "f", "d", "b"]
arr = [2, 3, 1, 9, 0, 4, 5, 7, 8, 6, 10]

arr.sort((a,b) => a-b)
arr.sort((a,b) => b-a)

arr = ['孙悟空','猪八戒','沙和尚','唐僧']

arr.forEach((Element,index,array) => {
console.log(Element,index,array)//Element,放在前面打印时,没有单引号
})

arr.forEach((Element,index) => console.log(index,Element))//Element放在后面打印时,有单引号,作为一个整体

arr = [1,2,3,4,5,6,7,8]
//获取数组中的所有偶数
let result = arr.filter((ele) => ele > 5)
result = arr.map((ele) => ele * 2)

arr = ['孙悟空','猪八戒','沙和尚']
result = arr.map((ele) => '<li>' + ele + '</li>')
console.log(result)

arr = [1, 2, 3, 4, 5, 6, 7, 8]

result = arr.reduce((a, b) => {
/*
1, 2
3, 3
6, 4
10, 5
*/
// console.log(a, b)

return a * b//累乘
})
// result = arr.reduce((a, b) => a + b, 10)
</script>