array.select() in javascript

前端 未结 5 2080
时光取名叫无心
时光取名叫无心 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:26

    Array.filter is not implemented in many browsers,It is better to define this function if it does not exist.

    The source code for Array.prototype is posted in MDN

    if (!Array.prototype.filter)
    {
      Array.prototype.filter = function(fun /*, thisp */)
      {
        "use strict";
    
        if (this == null)
          throw new TypeError();
    
        var t = Object(this);
        var len = t.length >>> 0;
        if (typeof fun != "function")
          throw new TypeError();
    
        var res = [];
        var thisp = arguments[1];
        for (var i = 0; i < len; i++)
        {
          if (i in t)
          {
            var val = t[i]; // in case fun mutates this
            if (fun.call(thisp, val, i, t))
              res.push(val);
          }
        }
    
        return res;
      };
    }
    

    see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter for more details

提交回复
热议问题