js 从数组中移除值

参考

https://exceptionshub.com/remove-a-value-from-an-array-in-coffeescript.html

Answers:

array.indexOf("World")will get the index of"World"or-1if it doesn’t exist.array.splice(indexOfWorld, 1)will remove"World"from the array.

 

Answers:

filter()is also an option:

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

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

 

Answers:

For this is such a natural need, I often prototype my arrays with anremove(args...)method.

My suggestion is to write this somewhere:

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

And use like this anywhere:

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

This way you can also remove multiple items at the same time:

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

 

Answers:

Checking if “World” is in array:

"World" in array

Removing if exists

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

or

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

Keeping reference (that’s the shortest I’ve found – !.push is always false since .push > 0)

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

 

Answers:

Try this :

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

 

Answers:

A combination of a few answers:

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

 

Answers:

_.without()function from the underscorejs library is a good and clean option in case you want to get a new array :

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

 

Answers:

CoffeeScript + jQuery:
remove one, not all

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

console.log arrayRemoveItemByValue(['2','1','3'],'3')
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值