javascript - js的shift()方法失效?
問題描述
如題,代碼如下:
<ul class='demo'> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> <li>6</li></ul><script> var l = document.getElementsByClassName('demo')[0]; var a = l.children; var r=a.shift(); console.log(r);//報錯:a.shift is not a function?</script>
類數(shù)組對象不能調(diào)用shift方法api?
問題解答
回答1:類數(shù)組不是數(shù)組,沒有繼承數(shù)組的相關(guān)api,可以用call或者apply來綁定this,比如
var r = [].shift.call(a)
ps: shift還涉及到操作數(shù)組的內(nèi)容,剛試了一下,強行用call來shift類數(shù)組對象,會報相關(guān)對象不能修改length的限定,如果還涉及dom的處理,建議還是用相關(guān)dom操作,比如removeChild啥的,這個就不擴展了。 dom類數(shù)組對象的相關(guān)資料可以在mdn找找,比如:https://developer.mozilla.org...
回答2:shift會修改原數(shù)組,導(dǎo)致length屬性改變,但是length是只讀的。通過下面方式可以使用。
<ul class='demo'> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> <li>6</li></ul></body><script> var l = document.getElementsByClassName('demo')[0]; var a = l.children; var arry = [...a]; var r=arry.shift(); console.log(r);</script>回答3:
當然,shift是數(shù)組的方法,可以先把類數(shù)組轉(zhuǎn)成數(shù)組再調(diào)用Array.prototype.slice.call(arraylike);
回答4:console.log(a)可以看到:__proto__:HTMLCollection HTMLCollection中并沒有shift方法。
相關(guān)文章:
1. docker不顯示端口映射呢?2. 學html時,點“運行實例”點“提交”,右邊的白框框沒任何反應(yīng)。3. javascript - vue 父子組件傳遞數(shù)據(jù)4. dockerfile - 我用docker build的時候出現(xiàn)下邊問題 麻煩幫我看一下5. javascript - 自執(zhí)行函數(shù)是當加載到這個js就執(zhí)行函數(shù)了嗎6. javascript - 怎么實現(xiàn)讓 div 里面的 img 元素 中心居中, 如下示例圖7. docker鏡像push報錯8. docker start -a dockername 老是卡住,什么情況?9. docker images顯示的鏡像過多,狗眼被亮瞎了,怎么辦?10. javascript - 微信小程序 如何實現(xiàn)這種左滑動出現(xiàn)刪除的辦法?有相關(guān)api嗎?
