JavaScript中的array.select()


81

JavaScript是否具有与Ruby类似的功能?

array.select {|x| x > 3}

就像是:

array.select(function(x) { if (x > 3)  return true})

Answers:


134

Array.filter()

var numbers = [1, 2, 3, 4, 5];
var filtered = numbers.filter(function(x) { return x > 3; });

// As a JavaScript 1.8 expression closure
filtered = numbers.filter(function(x) x > 3);

请注意,这Array.filter()不是标准的ECMAScript,它不会出现在早于ES5的ECMAScript规范中(感谢Yi Jiang和jAndy)。因此,其他ECMAScript方言(例如JScript(在MSIE上))可能不支持它。

2020年11月更新现在所有主流浏览器都支持Array.filter 。


6

Underscore.js是执行此类操作的良好库-如果可用,它使用诸如Array.filter之类的内置例程,否则使用它自己的例程。

http://documentcloud.github.com/underscore/

文档将给出一个使用思路-javascript lambda语法远不及ruby或其他语法(例如,我总是忘记添加一个显式return语句)简洁,而scope是另一种容易被发现的简便方法,但是您可以除了诸如惰性列表理解之类的构造之外,大多数事情都非常容易实现。

从文档中选择.select()(. filter()是相同的别名)

浏览列表中的每个值,返回所有通过真值测试(迭代器)的值的数组。委托本机过滤器方法(如果存在)。

  var evens = _.select([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });
  => [2, 4, 6]

5

你可以用这样的选择方法扩展你的JS

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

    return null;
};

现在您可以使用:

var x = [1,2,3,4];

var a = x.select(function(v) {
    return v == 2;
});

console.log(a);

或用于数组中的对象

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);

2
您的方法仅返回与之匹配的第一项,而不像ruby那样返回数组。尽管会有一点变化,但它会:Array.prototype.select = function(test){var new_array = [] for(var n = 0; n <this.length; n ++){if(test(this [n])) {new_array.push(this [n]); 返回new_array; };
丽贝卡·沃特伯里


4

Array.filter不是在许多浏览器中实现的,如果不存在此函数,则最好定义它。

Array.prototype的源代码发布在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;
  };
}

有关更多详细信息,请参见 https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/filter


kangax.github.io/compat-table/es5/#test-Array.prototype.filter上,如果选择“过时的平台”然后展开“ Array方法”,则他们会看到在以下位置不支持“ array.prototype.filter” IE8
George Birbilis
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.