js数据处理基础函数笔记

发布时间:2026/10/8 7:43:38
js数据处理基础函数笔记 js函数1、map函数map函数是一种高阶函数用于将一个函数应用于迭代器列表、数组等的每个元素并返回应用函数后的结果组成的新迭代器。例如const arr this.allData.map(d ({userName:d.userName, finalTotalAmount:d.finalTotalAmount}))这样就将allData的数组只筛选出了userName和finalTotalAmount的数据。2、find函数find函数通常用于在字符串中查找子串并返回子串第一次出现的索引位置从0开始string.find(substring, start, end)例如const exis acc.find(item item.userName curr.userName);3、reduce函数#定义一个函数用于将序列中的元素相加def sum(x, y):return x y#使用reduce函数对列表元素进行累加sequence [1, 2, 3, 4, 5]result reduce(sum, sequence)print(result)#输出15即12345的和例如// //相同数据相加 // //acc表示累积值curr表示当前值 const result arr.reduce((acc,curr) { const exis acc.find(item item.userName curr.userName); if (exis) { exis.finalTotalAmount curr.finalTotalAmount } else { acc.push(curr) } return acc; },[])4、filter函数用于根据指定条件筛选出符合条件的元素并返回一个新的迭代器。例如//过滤空数组 const arr2 arr1.filter(f {return f.userName ! null}) //筛选年龄大于20的,过滤其他并返回新的数组 const filterdata result.filter(f{return f.finalTotalAmount0 })5、forEach函数用于对数组中的每个元素执行指定操作的方法。它不返回新的数组而是在原数组上进行修改。例如// //查出现的次数 // const count {}; // arr2.forEach(obj { // if (count[obj.userName]) { // count[obj.userName]; // } else { // count[obj.userName] 1; // } // });6、sort函数用于对数组元素进行排序。它会原地修改数组并返回排序后的数组。A – b 为升序 b – a 为降序//升序取前二 filterdata.sort((a,b){return a.finalTotalAmount-b.finalTotalAmount})7、slice函数从数组中提取指定部分的方法。它不会修改原始数组而是返回一个新的数组。array.slice(startIndex, endIndex)其中array是要进行切片的数组startIndex是要开始切片的索引包括endIndex是要结束切片的索引不包括例如let result1 filterdata.slice(0,2);