How to avoid access mutable variable from closure

前端 未结 6 2020
醉梦人生
醉梦人生 2020-12-02 20:10

I have some code like this:

for(var id=0; id < message.receiver.length; id++){
   var tmp_id = id;
   zlib.gzip(JSON.stringify(message.json), function(err         


        
6条回答
  •  悲&欢浪女
    2020-12-02 21:06

    @user24359 answer is a good solution but you can simply replace the var keyword by the let keyword.

    for(var id=0;
    

    becomes

    for(let id=0;
    

    See details here.

    Edit : As Heriberto Juárez suggested it, it will only works for browsers that supports EcmaScript6.

提交回复
热议问题