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. mac连接阿里云docker集群,已经卡了2天了,求问?2. nginx英文文档的WebSocket proxying部分没看太明白,麻烦推荐一点中文文章3. android 文件File删除问题4. mysql优化 - mysql慢查询copying to tmp table5. angular.js - 怎样在使用ng-repeat属性的标签里面监听单个事件,使其能够单个改变CSS。6. css - transform: translateY(-50%)在360浏览器极速模式下使得文字变模糊了7. 请教: 关于 python 反斜杠转义的疑问8. javascript - js 写一个正则 提取文本中的数据9. css - .clearfix:after中为什么设置display: table10. python - 关于matplotlib的x轴显示的问题
