用于从数组中删除项目的Splat

时间:2014-03-30 14:08:31

标签: coffeescript

虽然我知道splats,但我仍然无法完全掌握以下代码中的最后一行:

class Borrowable extends Decorator
  constructor: (@libraryItem) ->

  removeBorrower: (borrower) ->
    @borrowers[t..t] = [] if ( t = @borrowers.indexOf(borrower) ) > -1

顺便说一句,此代码是从https://github.com/aksharp/Design-Patterns/blob/master/CoffeeScript/Decorator.coffee

复制的

我假设这是Destructuring Assignment,我仍然无法理解他在幕后发生的事情。

你能帮忙澄清一下吗?

1 个答案:

答案 0 :(得分:1)

让我们仔细看看最后一行:

@borrowers[t..t] = [] if ( t = @borrowers.indexOf(borrower) ) > -1

我不确定这种形式是否算作解构分配,可能是。

首先,它调用@borrowers.indexOf(borrower)来检查borrower数组中是否存在@borrowers并获取它的索引。

使用borrower in @borrowers形式代替@borrowers.indexOf(borrower) > -1是常规的,但在这种情况下我们也需要元素的索引。

如果borrower中存在@borrowers,它会在索引@borrowerst

之间获得t数组的一部分
@borrowers[t..t]

这是[borrower],并将其分配给空数组[],从而从borrower数组中移除@borrowers

这是与此任务类似的js:

@borrowers.splice t, 1