Skip to content
本文总阅读量

迭代器模式

HTML

HTML
<html>
    <body></body>
</html>

JS

JS
var  each  =  function  (obj,  callback)  {
    console.log('obj instanceof Array-->>',  obj  instanceof  Array)
    if  (obj  instanceof  Array)  {
        // 迭代数组
        for  (let  i  =  0;  i  <  obj.length;  i++)  {
            callback.call(obj[i],  i,  obj[i]);
        }
    }  else  {
        // 迭代对象
        for  (let  i  in  obj)  {  // 迭代object对象
            value  =  callback.call(obj[i],  i,  obj[i]);
        }
    }
}


  
// 增加节点
var  appendDiv  =  function  (data)  {
    each(data,  function  (i,  n)  {
        console.log('context-->>>>',  this)
        var  div  =  document.createElement('div');
        div.innerHTML  =  n;
        document.body.appendChild(div);
    })
}


appendDiv([1,  7,  3,  4,  5,  6]);
appendDiv({  a:  1,  b:  2,  c:  3,  d:  4  });

输出

  • obj instanceof Array-->>,true
  • context-->>>>,1
  • context-->>>>,7
  • context-->>>>,3
  • context-->>>>,4
  • context-->>>>,5
  • context-->>>>,6
  • obj instanceof Array-->>,false
  • context-->>>>,1
  • context-->>>>,2
  • context-->>>>,3
  • context-->>>>,4