js数组去重最简单的方法&js数组map,reduce,filter的使用介绍

1 篇文章 0 订阅
1 篇文章 0 订阅
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <ol>
        <li>招商银行-招银网络科技</li>
        <li>https://cmbnt.cmbchina.com/</li>
    <ol>
    <ul>
        <li>招商银行-招银网络科技</li>
        <li>https://cmbnt.cmbchina.com/</li>
    <ul>
</body>
<script>
    var arr = [1,2,2,22,4,5,5,5]

//数组去重最简单方法
    var newArray = new Set(arr) 
    console.log('---',[...newArray]);
    
// map
    // map()方法定义在JavaScript的Array中,
    // 它返回一个新的数组,新返回数组中的每个元素为原始数组的每一个元素分别调用map中的回调函数处理后的值。
    // array.map(function(currentValue, index, arr), thisIndex)
    console.log(arr.map((cur,index)=>{
        if(cur%2==1) //奇数
            return cur+2000
        return cur
    }));
// reduce
    // 对数组中的所有元素调用指定的回调函数。
    // 该回调函数的返回值为累积结果,并且此返回值在下一次调用该回调函数时作为参数提供。
    // array.reduce(function(pre, currentValue, currentIndex, arr), initialValue)
    // 1、previousValue (上一次调用回调返回的值,或者是提供的初始值(initialValue))
	//     2、currentValue (数组中当前被处理的元素)
	//     3、index (当前元素在数组中的索引)
	//     4、array (调用 reduce 的数组)
	// initialValue (作为第一次调用 callback 的第一个参数。)

    var t = arr.reduce((pre,cur,index)=>{
            pre[index] = cur
            return pre
    },{})
    console.log(t);

//filter
// filter为数组中的每个元素都执行一次callback函数,
// 并且将能够使callback函数返回true或者与true等价的值的元素组合成一个新的数组
// filter用法:Arrary.filter(callback(element,[index],[array]),[thisArg])
// 参数:
//     callback:数组元素执行的回调函数
//     element:当前正在处理的元素
//     index:当前正在处理的元素的索引值
//     array:调用 filter 方法的数组
//     thisArg:执行callback时,用于this的值
    var filter = arr.filter((cur,index)=>{
        if(cur%2==1) return true
    })
    console.log(filter);
</script>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

乐邂逅

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值