<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>