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. python如何不改动文件的情况下修改文件的 修改日期2. angular.js - 不适用其他构建工具,怎么搭建angular1项目3. angular.js - Angular路由和express路由的组合使用问题4. python - django 里自定义的 login 方法,如何使用 login_required()5. java8中,逻辑与 & 符号用在接口类上代表什么意思6. mysql优化 - mysql count(id)查询速度如何优化?7. mysql主从 - 请教下mysql 主动-被动模式的双主配置 和 主从配置在应用上有什么区别?8. 主从备份 - 跪求mysql 高可用主从方案9. node.js - node_moduls太多了10. python - 关于ACK标志位的TCP端口扫描的疑惑?
