ajs*_*sie 47 javascript node.js coffeescript
我有一个数组:
array = [..., "Hello", "World", "Again", ...]
Run Code Online (Sandbox Code Playgroud)
我怎么能检查阵列中是否有"世界"?然后删除它,如果它存在?并提到"世界"?
有时候我可能想用正则表达式匹配一个单词,在这种情况下我不会知道确切的字符串所以我需要引用匹配的字符串.但在这种情况下,我肯定知道这是"世界",这使它更简单.
谢谢你的建议.我找到了一个很酷的方法:
Ric*_*asi 72
filter()
也是一个选择:
arr = [..., "Hello", "World", "Again", ...]
newArr = arr.filter (word) -> word isnt "World"
Run Code Online (Sandbox Code Playgroud)
Ry-*_*Ry- 60
array.indexOf("World")
将获得索引"World"
或-1
如果它不存在.array.splice(indexOfWorld, 1)
将从"World"
数组中删除.
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)