在寫解析表達式的時候因爲循環遍歷從表達式截取下來的字符串數組,再加上要在商品列表中作相應的篩選。就是從一個商品列表中篩選出符合條件的商品進入到下一次篩選,因而我想到了用underscore裏邊的filter方法來減小代碼,以下:數組
1 for (var j = 0; j < temp.length; j++) { 2 if (temp[j].indexOf("==") != -1) { 3 temp[j] = temp[j].replace(/[']/g, ""); 4 var the_key = temp[j].split("==")[0]; 5 var the_value = temp[j].split("==")[1]; 6 _.filter(item_list, function (item) { 7 return has_the_property(item.properties, the_key, the_value) 8 }) 9 10 } else if (temp[j].indexOf("<") != -1) { 11 } else if (temp[j].indexOf(">") != -1) { 12 } 13 }
就是這種在一個for循環中嵌套一層帶有回調函數的方法,這個時候以上藍色加粗的變量 the_key,the value就會被提示mutable variable accessible from closure,大概是在這個關閉中有會發生改變的變量。由於有一個回調函數,而回調函數並不會順序的被執行,也就是可能回調函數還沒執行for循環已經到了下一次循環,或者下幾回循環。這樣不肯定的行爲顯然在程序中是不科學的,因此這麼寫就會報錯。函數
解決辦法:post
一、那就是不要這樣寫,在循環中不要使用這種帶有回調函數的方法。spa
二、寫成以下這種形式code
1 for(var j=0; j<temp.length; j++) { 2 (function(){ 3 ... 4 })(j) 5 }
好吧就這樣了,這兩種辦法能夠應付這種情況了。。。blog