Javascript javascript中的array.select()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4990175/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 15:06:27  来源:igfitidea点击:

array.select() in javascript

javascriptarrays

提问by pierrotlefou

Does javascript has similar functionality as Ruby has?

javascript 是否具有与 Ruby 相似的功能?

array.select {|x| x > 3}

Something like:

就像是:

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

回答by BoltClock

There is Array.filter():

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

Note that Array.filter()is not standard ECMAScript, and it does not appear in ECMAScript specs older than ES5 (thanks Yi Jiang and jAndy). As such, it may not be supported by other ECMAScript dialects like JScript (on MSIE).

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

回答by Tim

Underscore.js is a good library for these sorts of operations - it uses the builtin routines such as Array.filter if available, or uses its own if not.

Underscore.js 是这些类型操作的一个很好的库——如果可用,它使用内置例程,例如 Array.filter,否则使用它自己的例程。

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

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

The docs will give an idea of use - the javascript lambda syntax is nowhere near as succinct as ruby or others (I always forget to add an explicit return statement for example) and scope is another easy way to get caught out, but you can do most things quite easily with the exception of constructs such as lazy list comprehensions.

文档将给出使用的想法 - javascript lambda 语法远不及 ruby​​ 或其他语法那么简洁(例如,我总是忘记添加显式返回语句),范围是另一种容易被抓住的方法,但你可以这样做除了惰性列表推导式等结构外,大多数事情都很容易。

From the docs for .select() (.filter() is an alias for the same)

来自.select()的文档.filter() 是相同的别名)

Looks through each value in the list, returning an array of all the values that pass a truth test (iterator). Delegates to the native filter method, if it exists.

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

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

回答by silly

yo can extend your JS with a select method like this

你可以使用这样的 select 方法扩展你的 JS

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

回答by xinghua

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

Array.filter 很多浏览器都没有实现,如果不存在,最好定义这个函数。

The source code for Array.prototype is posted in MDN

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

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

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

回答by Starcat

There's also Array.find()in ES6 which returns the first matching element it finds.

Array.find()ES6 中也有它返回它找到的第一个匹配元素。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find

const myArray = [1, 2, 3]

const myElement = myArray.find((element) => element === 2)

console.log(myElement)
// => 2