繁体   English   中英

在 CoffeeScript 中从数组中删除一个值

[英]Remove a value from an array in CoffeeScript

我有一个数组:

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

如何检查“World”是否在数组中? 然后删除它,如果它存在? 并参考“世界”?

有时也许我想用正则表达式匹配一个单词,在这种情况下我不知道确切的字符串,所以我需要引用匹配的字符串。 但在这种情况下,我确定它是“世界”,这使它变得更简单。

感谢您的建议。 我找到了一个很酷的方法:

http://documentcloud.github.com/underscore

filter()也是一个选项:

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

newArr = arr.filter (word) -> word isnt "World"

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

因为这是一个很自然的需要,我经常使用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

并像这样在任何地方使用:

array = [..., "Hello", "World", "Again", ...]
ref = array.remove("World")
alert array # [..., "Hello", "Again",  ...]
alert ref   # "World"

通过这种方式,您还可以同时删除多个项目:

array = [..., "Hello", "World", "Again", ...]
ref = array.remove("Hello", "Again")
alert array # [..., "World",  ...]
alert ref   # ["Hello", "Again"]

检查“世界”是否在数组中:

"World" in array

如果存在则删除

array = (x for x in array when x != 'World')

要么

array = array.filter (e) -> e != 'World'

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

refs = []
array = array.filter (e) -> e != 'World' || !refs.push e

试试这个 :

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"]

几个答案的组合:

Array::remove = (obj) ->
  @filter (el) -> el isnt obj

_.without()来自underscorejs库的函数是一个不错的选择,如果你想获得一个新数组:

_.without([1, 2, 1, 0, 3, 1, 4], 0, 1)
[2, 3, 4]

CoffeeScript + jQuery:删除一个,而不是全部

arrayRemoveItemByValue = (arr,value) ->
  r=$.inArray(value, arr)
  unless r==-1
    arr.splice(r,1)
  # return
  arr

console.log arrayRemoveItemByValue(['2','1','3'],'3')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM