- // 无回调
- 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!
- */
- //该片段来自于http://www.codesnippet.cn/detail/280820135374.html
来源: http://www.codesnippet.cn/detail/280820135374.html