数组操作

//map()根据当前数组映射出一个新的数组,map和forEach等遍历方法不同,在forEach中return语句是没有任何效果的,而map则可以改变当前循环的值,返回一个新的被改变过值之后的数组(map需return),一般用来处理需要修改某一个数组的值。

let arr1 = [1,2,3];
let arr2 = arr1.map((value,key,arr) => {
console.log(value) // 1,2,3
console.log(key) // 0,1,2
console.log(arr) //[1,2,3] [1,2,3] [1,2,3] 有若干个值 就会遍历若干个自身的数组
return value * value;
})
console.log(arr1); // [ 1, 2, 3 ]
console.log(arr2); // [ 1, 4, 9 ]
————————————————

也可以遍历对象

let products= [
{ name: "马云", price: 200 },
{ name: "马化腾", price: 140 },
{ name: "马冬梅", price: 20 },
{ name: "马某", price: 10 }
]
var newProducts= products.map(product => {
return {
// 改变循环的值 得到一个新的数组
name: "**" + product.name + "**",
price: product.price / 2
};
});
console.log(newProducts)
/*
0: {name: "**马云**", price: 100}
1: {name: "**马化腾**", price: 70}
2: {name: "**马冬梅**", price: 10}
3: {name: "**马某**", price: 5}
*/
————————————————

//filter数组去重的操作

let arr = [1, 2, 2, 3, 4, 5, 5,5, 6,6,6,6];
let newArr = arr.filter((x, index,self)=>self.indexOf(x)===index)
console.log(newArr)
//newArr=[1,2,3,4,5,6]

//filter筛选数组对象

let arr = [
{a:'苹果',b:'面包',c:'吃'},
{a:'香蕉',b:'面包',c:'不吃'},
{a:'香蕉',b:'苹果',c:'吃'},
{a:'苹果',b:'香蕉',c:'不吃'},
]
console.log(arr.filter(item => item.a=== '苹果' ))
//[{a:'苹果',b:'面包',c:'吃'},{a:'苹果',b:'香蕉',c:'不吃'}]

//如果是多个条件的筛选的话 可以在item后加上这样类型的判断
//item => (a?item.a === a : true) && (b?item.b === b : true) && (c?item.c === c : true)
//a和b和c 的值都是需要我们提前预设的

//forEach遍历方式遍历数组全部元素,利用回调函数对数组进行操作,自动遍历数组.length次,且无法break中途跳出循环,不可控、不支持return操作输出,return只用于控制循环是否跳出当前循环
[1,2,3,4].forEach(n=>{ console.log(n) // 1 2 3 4 })

 

posted @ 2021-11-15 13:50  吴登峰  阅读(59)  评论(0)    收藏  举报