数组之filter方法

作者: 小雪洁 | 来源:发表于2020-03-16 13:58 被阅读0次
    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="utf-8">
            <title>filter过滤元素</title>
        </head>
        <body>
        </body>
        <script>
            let arr=["hxj","ydc","hwx"];
            //arr.filter(function(item,index,arr){})
            //遍历数组内所有元素,满足函数内条件的返回该元素,
            let newArr=arr.filter(function(item,index,arr){
                //return true;//newArr=["hxj", "ydc", "hwx"];
                return false;//newArr=[];
            });
            console.log(newArr);
            const users=[
                {name:"hxj",age:30},
                {name:"ydc",age:28},
                {name:"hwx",age:34},
            ];
            let newUser=users.filter(function(item){
                return item.age>=30;
            });
            console.log(newUser);//[{name:"hxj",age:30},{name: "hwx", age: 34}]
        
            //自定义一个过滤函数
            let a=[1,2,3,4,5];
            function filter(arr,callback){
                let newarr=[];
                for(let value of arr){
                    callback(value)==true?newarr.push(value):"";
                }
                return newarr;
            }
            console.log(filter(a,function(item){
                return item>2;
            }));//[3, 4, 5]
        </script>
    </html>
    
    

    相关文章

      网友评论

        本文标题:数组之filter方法

        本文链接:https://www.haomeiwen.com/subject/ojsgehtx.html