闭包-R和Javascript之间的区别

J

R和Javascript之间的具体区别是什么,这意味着在以下两个非常相似的示例中,我需要R版本中的其他行将参数值“固定”到第一个匿名函数?

是因为R将评估推迟到强制执行之前(就像我认为Lisp那样),但是Javascript会尽早评估吗?还是我错在这里?

R版

test <- list()
for (i in 1:10) {
  test[[i]] <- (function(index) {
    index <- index # why does R need this line when Javascript doesn't
    return (function() {
      print (index)
    })
  })(i)
}
test[[5]]()
test[[10]]()

Javascript版本

test = new Array()
for (var i=1; i<=10; i++) {
  test[i] = (function(index) {
    return function() {
      alert(index)
    }
  })(i)
}
test[5]()
test[10]()
里卡多·萨波特塔

R使用惰性评估。您不需要index <- index
可以使用force(index)


换句话说,index直到实际使用该值时,才计算该值。因此,如果在您传递参数和评估参数之间发生任何更改,则这些更改将反映在最终输出中。

force顾名思义,它强制对对象进行评估。

当您使用index <- index时,此时将创建具有相同名称的其他对象。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章