从 CoffeeScript 中的数组中删除一个值
我有一个数组:
array = [..., "Hello", "World", "Again", ...]
如何检查“World”是否在数组中? 如果存在的话将其删除? 并提到“世界”?
有时我可能想用正则表达式匹配一个单词,在这种情况下我不知道确切的字符串,所以我需要引用匹配的字符串。但在这种情况下,我确信它是“世界”,这使得它更简单。
感谢您的建议。我找到了一个很酷的方法:
I have an array:
array = [..., "Hello", "World", "Again", ...]
How could I check if "World" is in the array?
Then remove it if it exists?
And have a reference to "World"?
Sometimes maybe I wanna match a word with a regexp and in that case I won't know the exact string so I need to have a reference to the matched String. But in this case I know for sure it's "World" which makes it simpler.
Thanks for the suggestions. I found a cool way to do it:
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
filter()
也是一个选项:filter()
is also an option:array.indexOf("World")
将获得"World"
的索引,如果不存在则为-1
。array.splice(indexOfWorld, 1)
将删除 < code>“World” 来自数组。array.indexOf("World")
will get the index of"World"
or-1
if it doesn't exist.array.splice(indexOfWorld, 1)
will remove"World"
from the array.由于这是一种自然的需求,我经常使用
remove(args...)
方法对数组进行原型设计。我的建议是将其写在某个地方:
并在任何地方使用这样的方法:
这样您还可以同时删除多个项目:
For this is such a natural need, I often prototype my arrays with an
remove(args...)
method.My suggestion is to write this somewhere:
And use like this anywhere:
This way you can also remove multiple items at the same time:
检查“World”是否在数组中:
删除是否存在
或
保留引用(这是我发现的最短的 - !.push 始终为 false,因为 .push > 0)
Checking if "World" is in array:
Removing if exists
or
Keeping reference (that's the shortest I've found - !.push is always false since .push > 0)
试试这个:
Try this :
几个答案的组合:
A combination of a few answers:
underscorejs 库中的
_.without()
函数是一个很好且干净的选项如果你想获得一个新数组:_.without()
function from the underscorejs library is a good and clean option in case you want to get a new array :CoffeeScript + jQuery:
删除一个,而不是全部
CoffeeScript + jQuery:
remove one, not all