title: Strange Behavior of Loop in Javascript
body: <p>The following code is to generate bulletin board list. It works fine for viewing contents (eg, postId0, postId1, ...) but works as if 'i' were nPosts</p>
  
  <p>I recall that in C# I had the same problem and fixed by declaring a copy of i (var copy_i = i; inside the loop), but here that didn't work either.</p>
  
  <pre><code>function loadList() {
      $.getJSON("list.php", function (json) {
          var nPosts = json.length;
          for (var i = 0; i &lt; nPosts; i++) {
              var post = $('&lt;ol/&gt;', {
                  class: "viewPost",
                  id: "post" + i
              }).appendTo("#viewList");
  
              $('&lt;li/&gt;', {
                  class: "viewPostId",
                  id: "postId" + i,
                  text: json[i].noteId
              }).appendTo("#post" + i);
  
              var memo = $('&lt;li/&gt;', {
                  class: "viewMemo",
                  id: "memo" + i,
                  text: json[i].noteContent
              }).appendTo("#post" + i);
  
              //alerts 'nPosts' for every i.
              memo.on("click", function () { alert(i); });
          }
      });
  }
  </code></pre>