【js】map、filter、reduce、fill(待补充...)

const arr = [
	{ id: 1, flag: true },
	{ id: 2, flag: true },
	{ id: 3, flag: false },
	{ id: 4, flag: true },
]

map:返回的是对每个元素进行操作后的结果数组,这个数组的长度和原数组相同

const result = arr.map((item: any) => {
	return item.flag === false	
})
console.log(result)
// [false, false, true, false]

filter:返回的是原数组内满足条件的元素组成的新数组

const result = arr.filter((item: any) => {
	return item.flag === false
})
console.log(result)
// [{ id: 3, flag: false }]

reduce:数组的高阶函数,用于对数组的每一个元素进行归约操作,最终返回一个单一的值
reduce包含两个参数:

  • callback():回调函数,用于执行归约操作,它有四个参数:
    1. accumulator:累加器,累计回调函数的返回值,它是归约过程的中间结果
    2. currentValue:arr.reduce也是循环数组,currentValue就是当前循环到的数组中的每条数据
    3. currentIndex:索引
    4. array:原始数组
  • initValue:初始值,这个是可选参数,作为归约操作的初始值。
    1. 如果提供了初始值,则累加器accumulator将从初始值开始累计;
    2. 如果没有提供初始值,则累加器将从数组的第一个元素开始累计,跳过第一个元素。
Array.reduce(callback(accumulator, currentValue, currentIndex, Array), initValue)

举例说明reduce

const students = [
  { name: 'Alice', age: 20, score: 85 },
  { name: 'Bob', age: 21, score: 90 },
  { name: 'Charlie', age: 19, score: 95 },
  { name: 'David', age: 20, score: 80 },
]

const totalScore = students.reduce((accumulator, currentValue) => {
  return accumulator + currentValue.score
}, 0)

const averageScore = totalScore / students.length

console.log(averageScore)	// 87.5

fill:用于将数组中的元素替换为指定值,fill会修改原始数组,并返沪修改后的数组

  • value :要用来替换数组元素的值。
  • start :可选参数,指定替换开始的索引,默认为 0。
  • end :可选参数,指定替换结束的索引(不包含在内),默认为数组的长度。
arr.fill(value, start, end)
const arr = [1, 2, 3, 4, 5]
arr.fill(0, 2, 4)
console.log(arr)
// [1, 2, 0, 0, 5]
Array(5).fill('--')
// Array(number)用于创建一个指定长度的数组,比如:Array(5)创建了一个长度为5的新数组,该数组的每个元素都是undefined,再用fill给该数组中的值都替换为'--',就得到了['--', '--', '--', '--', '--']
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值