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. php laravel框架模型作用域2. java - 想在微信公众号下自定义菜单内搭建一个论坛,用到什么技术?3. css - 关于input标签disabled问题4. phpstudy v8 为什么网站刷新后会出现403错误?5. 微信$data =file_get_contents(’php://input’)取不到数据,抓包6. phpStudy2017轻巧版mysql无法启动7. Java中的BufferedImage在Android之中如何对应?8. redis - 腾讯的QQ平台如何维护庞大的在线用户列表?9. Spring数据mongodb审核不起作用(Java配置)10. 怎么让其他pc访问本地的phpstudy编写的网页
