Iterate Array Avoid Using for…in 和 for…of
Iterate 陣列時避免使用for…in, for…of 因可能有非預期的值出現。
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| var a = []; // Create a new empty array. a[5] = 5; // Perfectly legal JavaScript that resizes the array.
for (var i = 0; i < a.length; i++) { // Iterate over numeric indexes from 0 to 5, as everyone expects. console.log(a[i]); }
/* Will display: undefined undefined undefined undefined undefined 5 */ --------
var a = []; a[5] = 5; for (var x in a) { // Shows only the explicitly set index of "5", and ignores 0-4 console.log(x); }
/* Will display: 5 */
上述用同一個Example不同for方法~兩個例子會有不同的結果,且for...in是非預期的。 因此避免使用
|