0

我是咖啡脚本的新手,所以我想知道我是否做对了。我在 JavaScript 中有一个原始实现,forEach如下所示:

if(!Array.prototype.forEach){
   Array.prototype.forEach = function(callback, context){
     for(var i=0; i < this.length; i++){
        callback.call(context || null, this[i], i, this);
     }
   };
}

这是我目前在咖啡脚本中的编写方式

if not Array.prototype.forEach
    Array.prototype.forEach = (callback, context) ->
    context ?= null 
    callback context, @[i], i, @ for i in @ 

但我想知道它是否正确,尤其是上下文空检查似乎是多余的,以及上下文是否正确应用,就好像我仍在使用call. 我试图在咖啡脚本中查找一些示例,applycall到目前为止还没有那么幸运。

4

3 回答 3

2

in运算符的工作方式完全不同coffee-script。因此,在coffee-script您的代码中将如下所示:

Array::forEach ?= (callback, context) ->
  callback.call context, elem, i, @ for elem, i in @
  return

让我们看看这段代码。

Array::forEach只是一个快捷方式Array.prototype.forEach

?=意思是“如果没有分配就分配”。

for elem, i in smth是一种特殊形式的coffee-script in运算符,它允许您捕获元素的索引及其值。通常,for .. in ..运算符 incoffee-script仅对元素进行操作,而不对其索引进行操作。

return在函数末尾告诉编译器您不想返回最后一个操作的结果,在您的情况下是一个for循环。没有它,coffee-script它将捕获for循环内每个调用的结果,然后将它们全部作为单个数组返回。显然,您不希望完成这些额外的工作。

您可以将context变量的默认值设置为null,但这不是必需的,因为undefined其工作方式与 完全相同null。您当前的代码context = false在处理未定义的上下文中的处理方式相同。强制这种行为添加context ||= null到函数的开头,但这似乎是多余的。

您还可以使用js2coffee将您java-scriptcoffee-script.

于 2013-06-13T21:52:55.213 回答
2

上下文空检查似乎是多余的

好吧,它也设置contextnullif it was undefined。但是,它应该成为undefined实际。

上下文是否正确应用,就好像我仍在使用调用一样

不,因为你没有使用它。

更好

if not Array.prototype.forEach
    Array.prototype.forEach = (callback) ->
        context = arguments[1] if arguments.length > 1
        for el, i in @
            callback.call context, el, i, @ if i of @
        undefined
于 2013-06-13T18:01:36.793 回答
1

我赞成 Bergi 对解释的回答,但这里有一个稍微干净的版本,因为咖啡脚本参数可以有默认值。

if not Array.prototype.forEach
    Array.prototype.forEach = (callback,context = null) ->
        for i in @
            callback.call context, @[i], i, @ if i of @
        undefined
于 2013-06-13T21:02:08.717 回答