簡體   English   中英

閉包-R和Javascript之間的區別

[英]Closures - differences between R and Javascript

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時,此時您正在創建具有相同名稱的另一個對象。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM