HTML代碼:<ol id="test-list"> <li class="lang">Scheme</li> <li class="lang">JavaScript</li> <li class="lang">Python</li> <li class="lang">Ruby</li> <li class="lang">Haskell</li></ol>控制臺(tái):var list = document.getElementById('test-list')var slist = list.children;slist.sort(function(a, b){ return a.innerHTML > b.innerHTML ? 1 : -1 ;});這里報(bào)錯(cuò):Uncaught TypeError: slist.sort is not a function at <anonymous>:1:7 用typeof slist測試返回是"objiect"然后控制臺(tái)輸入:slist=Array.prototype.slice.call(slist);typeof slist;還是返回"objiect",但是這時(shí)控制臺(tái)輸入:slist.sort(function(a, b){ return a.innerHTML > b.innerHTML ? 1 : -1 ;});運(yùn)行正常,沒有報(bào)錯(cuò).排序結(jié)果也是對(duì)的,slist.forEach(function(el){ list.appendChild(el);})運(yùn)行后<ol id="test-list"><li class="lang">Scheme</li><li class="lang">JavaScript</li><li class="lang">Python</li><li class="lang">Ruby</li><li class="lang">Haskell</li></ol>我想問一下slist=Array.prototype.slice.call(slist);這一步起到了什么作用,為什么不能直接調(diào)用sort();;進(jìn)行排序?
關(guān)于Array.prototype.slice.call()的問題
莫回?zé)o
2019-02-11 16:16:04