使用coffeescript删除数组的重复元素

时间:2013-09-27 14:24:25

标签: javascript jquery coffeescript

我有一个元素重复的数组:

data = ["Ruby on rails", "Ruby on rails", "Jquery", "Coffescript", "Javascript"]

我尝试用

删除数组的重复元素
indexes = []
uniques = []
i = 0
while i < data.length
 if indexes[data[i].text] is "undefined"
  indexes[data[i].text] = "defined"
  uniques.push
i++
console.log data

但是我得到了与元素重复相同的结果。

我该如何修复?

谢谢!

1 个答案:

答案 0 :(得分:5)

… is "undefined"

确实编译为=== "undefined",这不是你想要的。删除不与字符串进行比较的引号,但删除undefined值。

顺便说一下,你的脚本应该是

index = {}
uniques = []

for text in data
 unless (text of index)
  index[text] = true
  uniques.push(text)

甚至像

这样的过滤器理解
index = {}
uniques = for text in data when not (text of index)
 index[text] = true
 text