js 数组对象操作
<script> //https://www.cnblogs.com/j-a-h/p/15698989.html //js 数组对象操作 (filter,finde、findIndex、map) // find、findIndex、map、filter var id = '1'; var arr = [ { id: '1', name: 'filter' }, { id: '2', name: '元素筛选出来' }, { id: '3', name: 'find ' }, { id: '4', name: 'findIndex ' }, ] // filter 过滤 根据条件对数组中元素进行筛选。返回符合条件的元素,组成一个新的数组, var filArr = arr.filter(function (item, index, arr) { if (item.id == id) { return item; } }) var filArr = arr.filter(item => item.id == id) console.log('filArr ', filArr); // find 查找 // find 找到数组中符合条件的元素,返回出来,只要找到符合条件的元素,就立刻返回该元素, // 不会再继续下去,所以find找的是一个元素 var arrfind = arr.find(function (item) { return item.id == id }) console.log('arrfind ', arrfind); // findIndex 找到符合条件元素的位置索引值 var idindex = arr.findIndex(function (item) { if (item.id == id) { return item; } }) console.log('idindex ', idindex); // .map 遍历返回一个新的数组,并且新数组的长度与原来的相同 // map方法里面也是一个回调函数,该函数也是接受三个参数,并且需要返回值, // index 索引值 arr 本身 //这个值将作为新数组里的元素,若是没有返回值,则为undefined 2 var mapArr = arr.map(function (item, index, arr) { return item; }) console.log(mapArr); //计算对象数组中某个属性的最大值 let max = Math.max.apply(null, arr.map(function (item) { return item.value; })); //计算对象数组中某个属性合计 function countTotal(arr, keyName) { let $total = 0; $total = arr.reduce(function (total, currentValue, currentIndex, arr) { return currentValue[keyName] ? (total + currentValue[keyName]) : total; }, 0); return $total; } var total = countTotal(arr, "属性名称"); </script>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理