1

これについての説明が欲しいです(javascriptkit.comから取得):

function buildList(list) {
  var result = [];
  for (var i = 0; i < list.length; i++) {
    var item = 'item' + list[i];
    result.push( function() {alert(item + ' ' + list[i])} );
  }
  return result;
}

function testList() {
  var fnlist = buildList([1,2,3]);
  // using j only to help prevent confusion - could use i
  for (var j = 0; j < fnlist.length; j++) {
    fnlist[j]();
  }
}

とてもtestList()簡単です。最初の関数を段階的にたどってみましたが、これが返されると考えたものです。

項目 1 1
項目 2 2
項目 3 3

私が得られないのは、 が 3 回result返される方法ですitem 3 undefined-なぜ undefined なのか、なぜのみitem 3?

-私が学ぼうとしているのは、これを機能させることではなく、どの部分が欠けているのか、なぜ期待どおりに出てこないのかを理解することです.

4

2 に答える 2

4

What's the problem?

The function in the for loop has a reference to i but i is changing in each iteration, so when you call the function declared in the loop it will use i with it's last value(3).

A simple closure will save the index value untouched:

for (var i = 0; i < list.length; i++) {
    (function(index){
        var item = 'item' + list[index];  // why ?
        result.push( function() {alert(item + ' ' + list[index])} );    
    })(i);    
}

Note:

Why do you need var item = 'item' + list[index]; if you re-lookup the value in the list?

Update based on question changed,

Because i has the final value- 3 which makes your code in the final iteration:

// i equals to 2 here
var item = 'item' + list[i]; // gives item3
result.push( function() {alert(item + ' ' + list[i])} );
// now `i` is changed to three so we don't enter the loop.

Values:

  • item == "item3"
  • i == 3
  • list[i] == list[3] == undefined.
于 2013-03-21T12:24:46.627 に答える
1

によって返される配列には、同じクロージャーを共有する関数がbuildList含まれていることを理解することが重要です。3そのクロージャーのローカル変数が変更されるたびに、それを共有するすべての関数に影響します。つまり、結果のすべての関数のiitemおよび変数は同じです。listループが を反復した後list、 の値は にi等しいままであり、その変数への参照を共有3するため、 のすべての関数について真です。resultしたがって、質問への回答は次のようになります。

なぜ未定義?

なぜならlist[3] === undefined

なぜitem 3

item変数が最後に変更されたのは、その本体iが実行されたときであるため (したがって)2forlist[2] === 3item === 'item 3'

于 2013-03-21T12:46:00.263 に答える