Created
October 6, 2012 11:23
-
-
Save legendlee/3844668 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 无回调 | |
function isArray(o) { | |
return toString.apply(o) === '[object Array]'; | |
} | |
function foo(arr) { | |
console.log(arr); | |
if (isArray(arr)) { | |
for (i in arr) { | |
(function(j) { | |
setTimeout(function() { | |
foo(arr[j]); | |
}, 0); | |
})(i); | |
} | |
} | |
} | |
foo([[1, 2], [3, 4]]); | |
/* | |
输出: | |
[[1,2],[3,4]] | |
[1,2] | |
[3,4] | |
1 | |
2 | |
3 | |
4 | |
*/ | |
//有回调 | |
function isArray(o) { | |
return toString.apply(o) === '[object Array]'; | |
} | |
// 设置一个计数器,标识“已知的还未被遍历的元素数量”,起始值显然为1 | |
var cbCounter = 1; | |
function foo(arr, cb) { | |
cbCounter += isArray(arr) ? arr.length : 0; // 把子元素的数加上,因为子元素现在已知了 | |
console.log(arr); | |
if (isArray(arr)) { | |
for (i in arr) { | |
(function(j) { | |
setTimeout(function() { | |
foo(arr[j], cb); | |
}, 0); | |
})(i); | |
} | |
} | |
if ((--cbCounter === 0) && (typeof cb === 'function')) cb(); // 前面的--就是把自己刨出去 | |
} | |
foo([[1, 2], [3, 4]], function() { | |
console.log('I am a callback!'); | |
}); | |
/* | |
输出: | |
[[1,2],[3,4]] | |
[1,2] | |
[3,4] | |
1 | |
2 | |
3 | |
4 | |
I am a callback! | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment