var it=values(,,,,,,,,);it.next();//it.next();//it.next();//分析:由于values函数需要接收任意多个参数,这里就需要用到上一节讲到的构建可变参数的函数的方法。然后里面的迭代器对象来遍历arguments对象的元素。
function values(){var i=,n=arguments.length;return {hasNext:function(){return i<n;},next:function(){if(this.hasNext()){return arguments[i++];}throw new Error("已经到达最后啦");}}}用上面的测试代码进行测试var it=values(,,,,,,,,);it.next();//undefinedit.next();//undefinedit.next();//undefined错误分析
function values(){var i=,n=arguments.length;//这里没有错误,arguments是values里的内置对象return {hasNext:function(){return i<n;},next:function(){if(this.hasNext()){return arguments[i++];//错误出现在这里,arguments是next方法函数的内置对象。}throw new Error("已经到达最后啦");}}} 这里的指代错误,很像是另一个让人头痛的对象this。处理this的指向时,通常是使用变量和保存正确的this。然后在其它地方使用这个变量。那么arguments对象的解决方案就出来了,借助一个变量来存储,这样arguments对象的指代就没有问题了。function values(){var i=,n=arguments.length,arg=arguments;return {hasNext:function(){return i<n;},next:function(){if(this.hasNext()){return arg[i++];}throw new Error("已经到达最后啦");}}} 运行测试代码var it=values(,,,,,,,,);it.next();//it.next();//it.next();//结果和预期的相同。

迭代器js实现
对设计模式了解一点点,但具体项目中,有得多的也就是工厂模式,其它很少用,下面是一个简单的实现,不对的地方,欢迎交流。
代码如下
function List(){this.data=[];}List.prototype={add:function(){var args=[].slice.call(arguments)this.data=this.data.concat(args); },remove:function(i){this.data.splice(i,);},iterator:function(){return new Iterator(this);}}function Iterator(list){this.list=list;this.cur=;};Iterator.prototype={hasNext:function(){return this.cur<this.list.data.length-;},next:function(){if(this.hasNext()){return this.list.data[this.cur++];}throw new Error("已经到底了~");},remove:function(){this.list.remove(this.cur);}}var list=new List();var it=list.iterator();list.add(,,,,,,,,);it.next();//it.next();//it.next();// 以上所述是小编给大家介绍的JS中使用变量保存arguments对象的方法,希望对大家有所帮助!