数组的遍历-reduce

普通数组的求和

var arr=[1,2,3,4,5]
	var arrTemp=arr.reduce((a,b)=>{
		return a+b
	},0)
	console.log(arrTemp,'arrTemp')  //15

数组中的对象的求和:

var arr=[
		{
			name:'小明',
			age:3
		},
		{
			name:'小红',
			age:5
		},
		{
			name:'小粉',
			age:12
		},
		{
			name:'小绿',
			age:4
		}
	]
	var arrTemp=arr.reduce((a,b)=>{
		return a+b.age   //很久没用了,然后有一次写成了a.age+b.age,接着报错
	},0)
	console.log(arrTemp,'arrTemp') //24
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
1. findIndex() - 返回数组中满足条件的第一个元素的索引,如果没有符合条件的元素,则返回 -1。 语法:array.findIndex(callback(element[, index[, array]])[, thisArg]) 参数: callback:用来测试每个元素的函数,返回 true 表示当前元素符合条件,false 则不符合。 element:当前遍历到的元素。 index:当前遍历到的元素的索引。 array:数组本身。 thisArg:可选,执行 callback 函数时使用的 this 值。 示例: const arr = [1, 2, 3, 4, 5]; const index = arr.findIndex((element) => element > 3); console.log(index); // 3 2. filter() - 返回一个新数组,其中包含原数组中所有符合条件的元素。 语法:array.filter(callback(element[, index[, array]])[, thisArg]) 参数: callback:用来测试每个元素的函数,返回 true 表示当前元素符合条件,false 则不符合。 element:当前遍历到的元素。 index:当前遍历到的元素的索引。 array:数组本身。 thisArg:可选,执行 callback 函数时使用的 this 值。 示例: const arr = [1, 2, 3, 4, 5]; const newArr = arr.filter((element) => element > 3); console.log(newArr); // [4, 5] 3. reduce() - 通过对数组中的每个元素进行归纳操作,将数组归纳为单个值。 语法:array.reduce(callback(previousValue, currentValue[, index[, array]])[, initialValue]) 参数: callback:归纳操作的函数,包含两个参数: previousValue:先前归纳操作的结果,或者在第一次调用时是 initialValue。 currentValue:当前遍历到的元素。 index:当前遍历到的元素的索引。 array:数组本身。 initialValue:可选,作为归纳操作的初始值。 示例: const arr = [1, 2, 3, 4, 5]; const sum = arr.reduce((previousValue, currentValue) => previousValue + currentValue, 0); console.log(sum); // 15

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值