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. mysql - JAVA怎么实现一个DAO同时实现查询两个实体类的结果集2. sql语句 - 如何在mysql中批量添加用户?3. mysql建表报错,查手册看不懂,求解?4. PHP类属性声明?5. 求大神支招,php怎么操作在一个html文件的<head>标记内添加内容?6. 怎么php怎么通过数组显示sql查询结果呢,查询结果有多条,如图。7. 致命错误: Class ’appfacadeTest’ not found8. 老师们php,插入数据库mysql,都是空的,要怎么解决9. mysql - 数据库建字段,默认值空和empty string有什么区别 11010. phpstady在win10上运行
