从CoffeeScript中的数组中删除值

ajs*_*sie 47 javascript node.js coffeescript

我有一个数组:

array = [..., "Hello", "World", "Again", ...]
Run Code Online (Sandbox Code Playgroud)

我怎么能检查阵列中是否有"世界"?然后删除它,如果它存在?并提到"世界"?

有时候我可能想用正则表达式匹配一个单词,在这种情况下我不会知道确切的字符串所以我需要引用匹配的字符串.但在这种情况下,我肯定知道这是"世界",这使它更简单.

谢谢你的建议.我找到了一个很酷的方法:

http://documentcloud.github.com/underscore

Ric*_*asi 72

filter() 也是一个选择:

arr = [..., "Hello", "World", "Again", ...]

newArr = arr.filter (word) -> word isnt "World"
Run Code Online (Sandbox Code Playgroud)

  • 重要的区别:这个解决方案不具有破坏性,即`arr`将保持不变(这通常是良好的功能实践).与接受的答案相比较,这是具有破坏性的. (3认同)

Ry-*_*Ry- 60

array.indexOf("World")将获得索引"World"-1如果它不存在.array.splice(indexOfWorld, 1)将从"World"数组中删除.

  • @ryanh:你是对的,更好的不是正确的词,但其他人提供了利用CoffeeScript特定功能的替代品 (2认同)

Alv*_*nço 16

因为这是一种天生的需求,我经常用一种remove(args...)方法对我的数组进行原型设计.

我的建议是把它写在某个地方:

Array.prototype.remove = (args...) ->
  output = []
  for arg in args
    index = @indexOf arg
    output.push @splice(index, 1) if index isnt -1
  output = output[0] if args.length is 1
  output
Run Code Online (Sandbox Code Playgroud)

并在任何地方使用:

array = [..., "Hello", "World", "Again", ...]
ref = array.remove("World")
alert array # [..., "Hello", "Again",  ...]
alert ref   # "World"
Run Code Online (Sandbox Code Playgroud)

这样您还可以同时删除多个项目:

array = [..., "Hello", "World", "Again", ...]
ref = array.remove("Hello", "Again")
alert array # [..., "World",  ...]
alert ref   # ["Hello", "Again"]
Run Code Online (Sandbox Code Playgroud)


小智 14

检查"World"是否在数组中:

"World" in array
Run Code Online (Sandbox Code Playgroud)

删除是否存在

array = (x for x in array when x != 'World')
Run Code Online (Sandbox Code Playgroud)

要么

array = array.filter (e) -> e != 'World'
Run Code Online (Sandbox Code Playgroud)

保持参考(这是我发现的最短的 - !.push总是假的,因为.push> 0)

refs = []
array = array.filter (e) -> e != 'World' || !refs.push e
Run Code Online (Sandbox Code Playgroud)


小智 8

试试这个 :

filter = ["a", "b", "c", "d", "e", "f", "g"]

#Remove "b" and "d" from the array in one go
filter.splice(index, 1) for index, value of filter when value in ["b", "d"]
Run Code Online (Sandbox Code Playgroud)

  • 从数组中删除第二个最后一项时,这不会按预期工作.见http://jsfiddle.net/8v25L/ (2认同)