array.select() in javascript

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

    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.

    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.

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

    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]
    

提交回复
热议问题