Javascript Groovy.collect()是JS.map()的等价物吗?

Javascript Groovy.collect()是JS.map()的等价物吗?,javascript,groovy,Javascript,Groovy,Groovy.collect()是JS.map()的等价物吗?或者还有其他用途吗?是的,collect()允许您转换集合元素的类型或结构: def strings = [ '1', '2', '3' ] assert String == strings.first().getClass() def nums = strings.collect{ it as Integer } assert Integer == nums.first().getClass() 它还可以做其他一些事情(如初始收集

Groovy.collect()是JS.map()的等价物吗?或者还有其他用途吗?

是的,
collect()
允许您转换集合元素的类型或结构:

def strings = [ '1', '2', '3' ]
assert String == strings.first().getClass()
def nums = strings.collect{ it as Integer }
assert Integer == nums.first().getClass()

它还可以做其他一些事情(如初始收集),但在其他方面基本相同:

// Collect without
// initial collection.
assert [1,2,8] == [1,4,64].collect(Math.&sqrt)
assert [0,2,4,6] == (0..3).collect { it * 2 }
assert ['Groovy', 'Grails'] == [lang: 'Groovy', framework: 'Grails'].collect { it.value }
 
// Collect with initial collection argument.
assert [0, 1, 2, 3] == [2, 3].collect([0, 1]) { it }
assert [0, 3, 6, 9] == [2, 3].collect([0, 3], { it * 3})
assert ['Gradle', 'groovy', 'grails'] == ['Groovy', 'Grails'].collect(['Gradle']) { it.toLowerCase() }
assert ['m','r','h','a','k','i'] == [4, -3, 7, 5].collect(['m', 'r']) { (it + 100) as char }

注:我已经写了十几行Groovy,我甚至从来没有看过
。collect
,但它似乎是等效的。我花了很短的时间在谷歌上找到了那个。你有没有理由相信这两者是不相等的?因为除此之外,这似乎不是一个很好的问题。这个名字令人困惑。我的第一个想法是“也许它不完全相等”。。。谢谢您的解释!所以它们是不同的。只是
collect
可以迭代更多的东西(映射、字符串、其他对象、集合),而JavaScript中的
map
只在数组上运行。在groovy中对数组、列表或其他“集合”进行操作时,其功能与其他方面类似。另外:
[a:'1',b:'2'].collect{k,v->“$k$v”}