簡體   English   中英

從數組coffeescript中隨機選擇唯一元素

[英]randomly select unique element from array coffeescript

我想從一個數組中隨機選擇一個元素,該數組在coffeescript的另一個數組中不存在。

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

這也很可愛

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM