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>
類數組對象不能調用shift方法api?
問題解答
回答1:類數組不是數組,沒有繼承數組的相關api,可以用call或者apply來綁定this,比如
var r = [].shift.call(a)
ps: shift還涉及到操作數組的內容,剛試了一下,強行用call來shift類數組對象,會報相關對象不能修改length的限定,如果還涉及dom的處理,建議還是用相關dom操作,比如removeChild啥的,這個就不擴展了。 dom類數組對象的相關資料可以在mdn找找,比如:https://developer.mozilla.org...
回答2:shift會修改原數組,導致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是數組的方法,可以先把類數組轉成數組再調用Array.prototype.slice.call(arraylike);
回答4:console.log(a)可以看到:__proto__:HTMLCollection HTMLCollection中并沒有shift方法。
相關文章:
1. javascript - webpack 報錯 新人 求解2. nginx 80端口反向代理多個域名,怎樣隱藏端口的?3. android - NavigationView 的側滑菜單中如何保存新增項(通過程序添加)4. node.js - 跑antd的的模板例子!想修改端口,怎么修改呢!!(里面好像用了什么dora插件!!!)5. angular.js - angular做點擊購買時的遮罩層6. angular.js - 關于ng-model和ng-bind的疑問7. 有大佬知道這種接口文件怎么使用嗎?8. 關于thinkphp 5.1中,ajax提交數據url的格式寫法,加花括號就出錯,請老師指點9. tp5 不同控制器中的變量調用問題10. AirPods Pro 2連接Pixel 7出問題:播放90秒自動斷連
