https://www.cnblogs.com/woshidouzia/p/9304603.html
reduce
<!DOCTYPE html>
<html>
<head>
</head>
<body>
</body>
<script>
const data = {
business: [
{ a: 1 },
{ a: 1 },
{ a: 1 },
{ a: 1 }
],
it: [
{ a: 1 },
{ a: 1 },
{ a: 1 },
{ a: 1 }
],
sdf: [
{ a: 1 },
{ a: 1 },
{ a: 1 },
{ a: 1 }
]
}
//zhangyunfei
// 遍历对象的常用方法是 for...in 和 Object.keys 获取的是键名
for (let i in data) {
console.log(i)
}
// for of 遍历的是数组(value) for in遍历对象(key)
for (let m of data.sdf) {
console.log(m)
}
//获取对象的keys的值,是一个数组
const array= Object.keys(data)
// 等同于
const dsdf=Object.getOwnPropertyNames(data)
// array=['business', 'it', 'sdf']
const sdf = array.reduce((prev, cur)=>{
prev[cur] = data[cur].map((v)=>{
return{
...v,
key: cur
}
})
return prev
}, {})
console.log(sdf)
// 总结:
// 1.遍历对象的方法 for...in Object.keys(data) Object.getOwnPropertyNames(data)
// 2.遍历数组的方法 for...of map reduce for forEach filter find findIndex keys values entries
data.sdf.forEach((item,index,array)=>{
console.log(array)
})
// return 并不影响原来的数组,只是相当于把原数组克隆一份,把克隆的这一份的数组中的对应项改变了
const newSdf=data.sdf.map((item,index,array)=>{
// do something
return {a:222}
})
console.log('map',newSdf)
//filter 和 map 的值的区别 ,filter 相当于过滤器,过滤得到符合条件的数据,map返回的是一个boolean
const shuzu = [1, 2, 3, 4, 5, 6, 7, 8]
const newfilter= shuzu.filter((item,index,array)=>{
return item>4
})
console.log(newfilter) //[5, 6, 7, 8]
const newMap=shuzu.map((item,index,array)=>{
return item>4
})
console.log(newMap) //[false, false, false, false, true, true, true, true]
// every 检查每一项,需要全部为true才为true 否则是false every 和 some 正好相反
var arr = [7, 6, 8, 4, 5, 6];
console.log(arr.every(function (item, index, array) {
return item > 3;
}));
// reduce
const newReduce= [0, 1, 2, 3, 4].reduce(function (previousValue, currentValue, index, array) {
console.log('上值',previousValue)
console.log('现在的值', currentValue)
console.log('当前值的下标', index)
console.log('这个数组', array)
return previousValue + currentValue;
}, 5);
console.log(newReduce)
// find 遍历查找数据
var stu = [
{
name: '张三',
gender: '男',
age: 20
},
{
name: '王小毛',
gender: '男',
age: 20
},
{
name: '李四',
gender: '男',
age: 20
}
]
// 获取项
const newFind=stu.find((item,index,array)=>{
return item.name==='李四'
})
console.log(newFind) //{name: "李四", gender: "男", age: 20}
// 获取下标
const newFindIndex = stu.findIndex((item, index, array) => {
return item.name === '李四'
})
console.log(newFindIndex) //{name: "李四", gender: "男", age: 20}
</script>
</html>