[英]Coffeescript remove array value by index
I have an array of objects and I want to remove a value by its index. 我有一个对象数组,我想通过其索引删除一个值。 I have a method, to which the value to be removed is passed, that finds the passed parameter value:
我有一个方法,要传递的值被传递,找到传递的参数值:
remove: (val) ->
for el, index in @arr
if el is val
# remove el from @arr...
The CoffeeScript website says quite clearly that in order to replace the element I want, I have to do @arr[index] = 'something'
, but nothing is said for removing it entirely. CoffeeScript网站非常清楚地说明,为了替换我想要的元素,我必须做
@arr[index] = 'something'
,但没有任何内容可以完全删除它。
Just use .splice()
: 只需使用
.splice()
:
for index, elem in @arr
@arr.splice index, 1 if elem is val
If you don't care about Internet Explorer 7 or 8, you can simplify it even more: 如果您不关心Internet Explorer 7或8,则可以进一步简化:
@arr.splice @arr.indexOf(val), 1
This assumes that the element is present in the array, otherwise it would remove the very last element. 这假定元素存在于数组中,否则它将删除最后一个元素。 In case you need to check if it is present, you can use a little trick:
如果您需要检查它是否存在,您可以使用一个小技巧:
@arr.splice (@arr.indexOf(val)+1 or @arr.length+1)-1, 1
Compared to the "coffee only" filter solution, you get 4-8 times the performance (in Chrome): 与“仅咖啡”过滤解决方案相比,您可以获得4-8倍的性能(在Chrome中):
Removing 5 random elements from an array with 10.000.000 integers
从具有10.000.000个整数的数组中删除5个随机元素
cumulative execution time after each removed element
每个删除元素后的累积执行时间
filter method
过滤方法
- 197ms
197ms
- 422ms
422ms
- 626ms
626ms
- 847ms
847ms
- 1087ms
1087ms
splice method
拼接方法
- 33ms
为33ms
- 83ms
83ms
- 142ms
142ms
- 198ms
198ms
- 255ms
255毫秒
splice and indexOf method
splice和indexOf方法
- 27ms
27ms
- 70ms
70ms的
- 88ms
88ms
- 116ms
116ms
- 134ms
134ms
Test code - quick and dirty (doesn't account for randomly selecting the same value twice): 测试代码 - 快速和脏(不考虑随机选择相同的值两次):
log "coffee method"
arr = [0..9999999]
length = arr.length
start = new Date().getTime()
for num in [1..5]
val = Math.round(Math.random() * length)
do (val) -> arr = (x for x in arr when x isnt val)
log new Date().getTime()-start+"ms"
log "splice method"
arr = [0..9999999]
length = arr.length
start = new Date().getTime()
for num in [1..5]
val = Math.round(Math.random() * length)
for index, elem in arr
arr.splice index, 1 if elem is val
log new Date().getTime()-start+"ms"
log "splice method with indexOf()"
arr = [0..9999999]
length = arr.length
start = new Date().getTime()
for num in [1..5]
val = Math.round(Math.random() * length)
arr.splice arr.indexOf(val), 1
log new Date().getTime()-start+"ms"
Demo: http://jsfiddle.net/j9CZz/1/ 演示: http : //jsfiddle.net/j9CZz/1/
文档给出了使用过滤器的示例,所以也许你可以尝试一下?:
remove: (val) -> @arr = (x for x in @arr when x isnt val)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.