When to add return to filter in js

Conclusion: If you write {}, you need to return, if you don’t write {}, you don’t need to add return

Is it probably written in {} even if it is a function?

It should be that I didn’t learn the ES6 arrow function well

let arr = [
            {
    
    
                id: 1,
                name: 'aa',
                desc: 'aaaa'
            },
            {
    
    
                id: 2,
                name: 'bb'
            },
            {
    
    
                id: 3,
                name: 'aa'
            }
        ]
        let arr1 = arr.filter(item => item.name == 'aa')//正确
        // let arr2 = arr.filter(item =>  return item.name == 'aa' )  //报错
        let arr3 = arr.filter(item => {
    
    item.name == 'aa'})//为空
        let arr4 = arr.filter(item => {
    
     return item.name == 'aa' })//正确
        console.log(arr1, 'arr1') 
        // console.log(arr2, 'arr2');
        console.log(arr3, 'arr3');
        console.log(arr4, 'arr4');

insert image description here
arr1, arr4 can be output correctly, arr3 is empty without getting the correct value, and arr2 reports an error

Guess you like

Origin blog.csdn.net/Selina_lxh/article/details/129007592