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. js怎样实现在类似qq的联系人分组中进行搜索后,又可恢复原分组的界面?2. javascript - 百度地图一开始设置了中心点,怎么通过按钮在调转到对应的中心点????3. windows-server - 阿里云服务器给了权限,本地采集的数据远程写入服务器中MySQL5.5表中,一秒可以写入多少?这个速度一般由什么来决定?4. MongoDB的索引需要考虑每个键的索引方向,为何这么设计?而MySQL的索引则无需考虑方向,两者之间有何优劣势?5. javascript - 微信 H5 授权 返回键6. mysql优化 - mysql 一张表如果不能确保字段列长度一致,是不是就不需要用到char。7. python - 如何将文本文件的CR换行符换成LF换行符?8. 怎样用python给mp3添加封面?9. TP6里多应用里如何开启调试跟踪10. 数据库 - Mysql的存储过程真的是个坑!求助下面的存储过程哪里错啦,实在是找不到哪里的问题了。