迭代器示例
題目:希望編寫一個便利的函數(shù),它可以接收任意數(shù)量的參數(shù),并為這些值建立一個迭代器。
測試代碼好下:
var it=values(,,,,,,,,); it.next();// it.next();// it.next();//
分析:由于values函數(shù)需要接收任意多個參數(shù),這里就需要用到上一節(jié)講到的構(gòu)建可變參數(shù)的函數(shù)的方法。然后里面的迭代器對象來遍歷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("已經(jīng)到達最后啦"); } } }
用上面的測試代碼進行測試
var it=values(,,,,,,,,); it.next();//undefined it.next();//undefined it.next();//undefined
錯誤分析
代碼運行結(jié)果并不正確,下面就對初始的編碼程序進行分析。
function values(){ var i=,n=arguments.length;//這里沒有錯誤,arguments是values里的內(nèi)置對象 return { hasNext:function(){ return i<n; }, next:function(){ if(this.hasNext()){ return arguments[i++];//錯誤出現(xiàn)在這里,arguments是next方法函數(shù)的內(nèi)置對象。 } throw new Error("已經(jīng)到達最后啦"); } } }
這里的指代錯誤,很像是另一個讓人頭痛的對象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("已經(jīng)到達最后啦"); } } }
這里的指代錯誤,很像是另一個讓人頭痛的對象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("已經(jīng)到達最后啦"); } } }
運行測試代碼
var it=values(,,,,,,,,); it.next();// it.next();// it.next();//
結(jié)果和預(yù)期的相同。
提示
當引用arguments時當心函數(shù)嵌套層級
綁定一個明確作用域的引用到arguments變量,從而可以在嵌套的函數(shù)中引用它
附錄一:迭代器
迭代器(iterator)有時又稱游標(cursor)是程序設(shè)計的軟件設(shè)計模式,可在容器上遍歷的接口,設(shè)計人員無需關(guān)心容器的內(nèi)容。
迭代器UML類圖
迭代器js實現(xiàn)
對設(shè)計模式了解一點點,但具體項目中,有得多的也就是工廠模式,其它很少用,下面是一個簡單的實現(xiàn),不對的地方,歡迎交流。
代碼如下
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('已經(jīng)到底了~'); }, 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對象的方法,希望對大家有所幫助!
更多JS中使用變量保存arguments對象的方法相關(guān)文章請關(guān)注PHP中文網(wǎng)!
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時與本網(wǎng)聯(lián)系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com