filter()遍歷注意事項:數組
1.未被賦值的元素不會被遍歷到 spa
2.在遍歷開始後添加到數組的元素不會被遍歷到code
3.被刪除的元素不會被遍歷到blog
4.在遍歷該項以前,能夠更改該項值索引
1.ip
<script> var a = [1,2,3]; a[6] = 10; console.log(a);//[1, 2, 3, empty × 3, 10] var obj = { suc:"yes", fail:undefined } var result = a.filter(function(value,index){ if(value === undefined) return obj.suc },obj); console.log(result);//[] </script>
結果爲空數組io
雖然a[5]的輸出是unfined,可是a[5]做爲未被賦值項,不會被filter()遍歷console
<script> var a = [1,2,3,void 0,4,5,void 0,6,void 0,7]; var obj = { suc:"yes", fail:undefined } var result = a.filter(function(value,index){ if(value === undefined) return obj.suc },obj); console.log(result); </script>
結果:[undefined,undefined,undefined]function
數組未被賦值項的undefined和顯式賦值undefined是不一樣的。這裏的3,6,8項會被遍歷到class
2.
<script> var a = [1,2,3,4,5,6,7,8,9]; var obj = { suc:"yes", fail:undefined } var result = a.filter(function(value,index){ if(index == 0)a[9] = 10; return !(value%2); },obj); console.log(result); </script>
結果:[2,4,6,8]
雖然在遍歷到第一個元素時,就爲數組添加了新元素a[9],可是新元素不會被遍歷到。被遍歷的元素是遍歷開始的時候,數組的一個快照。注意這個快照只關注數組的索引項,而不是索引項值,下面的例子有解釋
3.
<script> var a = [1,2,3,4,5,6,7,8,9]; var obj = { suc:"yes", fail:undefined } var result = a.filter(function(value,index){ if(index == 0)delete a[1]; return !(value%2); },obj); console.log(result); </script>
結果:[4,6,8]
索引號1被刪除,不會出如今遍歷中
打印數組a:
[1, empty, 3, 4, 5, 6, 7, 8, 9]
4.
<script> var a = [1,2,3,4,5,6,7,8,9]; var obj = { suc:"yes", fail:undefined } var result = a.filter(function(value,index){ if(index == 0)a[1] = 10; return !(value%2); },obj); console.log(result); </script>
結果:[10,4,6,8]
<script> var a = [1,2,3,4,5,6,7,8,9]; var obj = { suc:"yes", fail:undefined } var result = a.filter(function(value,index){ if(index == 3)a[1] = 10; return !(value%2); },obj); console.log(result); </script>
結果:[2,4,6,8]
某個項值在遍歷以後更改,就已經來不及了