我想从 coffeescript 中另一个数组中尚不存在的数组中随机选择一个元素。
咖啡脚本中有什么东西可以简化吗?怎么能做到这一点呢?谢谢
它不是特别像CoffeeScript,但这样的东西可以解决问题:
filterAndRandomSelect = (arr1, arr2) ->
filtered = (i for i in arr1 when i not in arr2) #this is pretty cute
filtered[Math.floor(Math.random() * filtered.length)]
console.log filterAndRandomSelect [1, 2, 3, 4, 5], ['a', 'b', 'c', 4, 5]
当然,那条"可爱"的CS台词也很容易:
filtered = arr1.filter (val) -> val not in arr2
这也有点可爱。