【问题标题】:CoffeeScript extend operator modifying 'this'?CoffeeScript 扩展运算符修改“this”?
【发布时间】:2012-02-22 23:45:46
【问题描述】:

我最近偶然发现了一些东西。我想添加从数组中删除对象的功能,如下所示:

someArray.remove(element)

我想使用 CoffeeScript 的 extend 运算符并执行以下操作:

Array::remove = (element) ->
  return false unless _.include(this, element)
  this = this.splice(_.indexOf(this, element), 1)
  true

但是创建的原型函数将this指向Array对象本身,所以唯一的方法是返回一些东西,看起来像这样:

someArray = someArray.remove(element)

以及这样的实现:

Array::remove = (element) ->
  return this unless _.include(this, element)
  this.splice(_.indexOf(this, element), 1)

在 ruby​​ 中,这是 joinjoin! 之间的确切区别。

有什么办法可以做到吗?

【问题讨论】:

    标签: ruby coffeescript this prototype extend


    【解决方案1】:

    我认为你对splice 有误解。它对阵列本身进行操作。这似乎可以解决问题,除非我完全误解了您的问题:

    _ = require "underscore"
    
    Array::remove = (element) ->
      index = _.indexOf @, element
      return false if index is -1
      @splice index, 1
      true
    
    foo = ["a", "b", "c"]
    console.log foo            # => ['a', 'b', 'c']
    console.log foo.remove "b" # => true
    console.log foo            # => ['a', 'c']
    console.log foo.remove "d" # => false
    console.log foo            # => ['a', 'c']
    

    请注意,coffeescript 包含一个用于 indexOf 的 shim,因此下划线不是严格需要的,因此您可以这样做:

    Array::remove = (element) ->
      index = @indexOf element
      return false if index is -1
      @splice index, 1
      true
    

    【讨论】:

    • 谢谢你,你是对的!不知道splice其实是在修改数组,还以为只是返回一个新副本。
    【解决方案2】:

    我将它实现为:

    Array::remove = (element) ->
      return false unless element in @
      @splice(@indexOf(element), 1)
      true
    

    而且效果很好。我不确定您对this 变量有什么问题,但您应该注意splice 更改了原始数组,因此不需要分配。您的第一个实现甚至无法为我编译,因为 CoffeeScript 不允许您分配给 this

    【讨论】:

    • 也谢谢你,一个非常优雅的解决方案!太好了!
    猜你喜欢
    • 1970-01-01
    • 2020-08-25
    • 1970-01-01
    • 2019-01-17
    • 1970-01-01
    • 1970-01-01
    • 2017-12-20
    • 2016-09-20
    • 2020-04-13
    相关资源
    最近更新 更多