array.select() in javascript

前端 未结 5 2068
时光取名叫无心
时光取名叫无心 2021-01-31 06:44

Does javascript has similar functionality as Ruby has?

array.select {|x| x > 3}

Something like:

array.select(function(x) { i         


        
5条回答
  •  鱼传尺愫
    2021-01-31 07:20

    yo can extend your JS with a select method like this

    Array.prototype.select = function(closure){
        for(var n = 0; n < this.length; n++) {
            if(closure(this[n])){
                return this[n];
            }
        }
    
        return null;
    };
    

    now you can use this:

    var x = [1,2,3,4];
    
    var a = x.select(function(v) {
        return v == 2;
    });
    
    console.log(a);
    

    or for objects in a array

    var x = [{id: 1, a: true},
        {id: 2, a: true},
        {id: 3, a: true},
        {id: 4, a: true}];
    
    var a = x.select(function(obj) {
        return obj.id = 2;
    });
    
    console.log(a);
    

提交回复
热议问题