Correctly understand the difference between map, foreach and filter

foreach

(1) Suppose we have an array, and each element is a person. A line of people stood in front of you.
Foreach is what you do with them one by one in order, what to do, whatever you want:

var darr = [{
    
    name:'张三'},{
    
    name:'李四'},{
    
    name:'赵六'}]
darr.forEach((item)=>{
    
    
    item.sex='男'
})
console.log(darr)
//输出结果: darr =[{name: "张三", sex: "男"},{name: "李四", sex: "男"},{name: "赵六", sex: "男"}]

map

The map is that you hold a box (a new array) in your hand and ask them to throw the wallet in one by one. At the end you get a new array, which contains everyone's wallets. The order of the wallets corresponds to the order of the people.

var darr = [{
    
    name:'张三'},{
    
    name:'李四'},{
    
    name:'赵六'}]
var newarr = darr.map((item)=>{
    
    
  return  item.sex='男'
})
console.log(newarr)
//则会输出 newarr =["男", "男", "男"]

var darr = [{
    
    name:'张三'},{
    
    name:'李四'},{
    
    name:'赵六'}]
var newarr = darr.map(function (item) {
    
    
  return {
    
    name: item.name, sex: '男'}
})
console.log(newarr)
//输出结果: darr =[{name: "张三", sex: "男"},{name: "李四", sex: "男"},{name: "赵六", sex: "男"}]

filter

When you count the wallets one by one, don't leave the money in the original box with less than 100 yuan (leave it in the original box), and throw it in a new box with more than 100 yuan. At the end of this, you have a new array, which contains all wallets with more than 100 yuan:

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_45432996/article/details/111378140