Coffeescript:数组元素匹配另一个数组 [英] Coffeescript: Array element matches another array

查看:170
本文介绍了Coffeescript:数组元素匹配另一个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个数组:

array1 = ["hello","two","three"]
array2 = ["hello"]



我想检查array2是否包含1个或多个array1个字。

I want to check if array2 contains 1 or more array1 words.

如何使用Coffeescript?

How can I do that using Coffeescript?

推荐答案

方法使用此CoffeeScript 章检查两个数组之间的交集。 CoffeeScript看起来非常棒。

Found a way to check for the intersection between two arrays using this CoffeeScript chapter. CoffeeScript seems pretty awesome looking at this.

如果在元素的交集之后产生的数组包含至少一个项,那么这两个数组都有共同的元素。 / p>

If the array resulting after the intersection of the elements contains at least one item, then both arrays have common element(s).

intersection = (a, b) ->
  [a, b] = [b, a] if a.length > b.length
  value for value in a when value in b

x = ["hello", "two", "three"]
y = ["hello"]

intersection x, y  // ["hello"]

href =http://jashkenas.github.com/coffee-script/#try%3a%20%20%20%20intersection%20%3D%20%28a%2C%20b%29%20-%3E%0A %20%20%20%20%20%20%5Ba%2C%20b%5D%20%3D%20%5Bb%2C%20a%5D%20if%20a.length%20%3E%20b长度% %20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20% %22%2C%20%22%2%22%2C%20%22%22%5D%0A%20%20%20%20%3D%20%5B%22% %20%20%0A%20%20%20%20console.log%28intersection%20x%2C%20y%29>这里。

Try it here.

这篇关于Coffeescript:数组元素匹配另一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆