首页 > 在NodeList上应用splice.call出错,为什么呢?

在NodeList上应用splice.call出错,为什么呢?

菜鸟求教:

有个场景,需要对已经取出的NodeList进行重新排序,把node1插入到Node2后面。代码如下:

var cols = document.querySelectorAll("ul>li");
var target = cols[0];
[].splice.call(cols,[0, 1]);
[].splice.call(cols,[3, 0, target]);

抛错:Uncaught TypeError: Cannot set property length of #<NodeList> which has only a getter

请问各位大神,splice方法哪里用错了呢?


1.函数对象的call方法第2个以后的参数不是一个数组,需要把多个参数依次传入
apply方法第2个参数是一个数组
2.NodeList它的长度不能被修改,那么也就是意味着通过splice方法不会有作用(splice方法会修改原始对象,并修改其长度属性)
规范有云:

Attributes
length of type unsigned long, readonly
The number of nodes in the list. The range of valid child node indices is 0 to length-1 inclusive.


document.querySelectorAll("ul>li")返回的NodeList不是数组,只是类数组(Array-like Object)。
报错已经跟你说的很清楚了,你不能给类数组添加新的值,因为类数组是只读的,只有getter没有setter,你调用的splice是对cols进行了修改,这是不允许的。
ps:[].splice.call(cols,[0, 1])相当于cols.splice([0,1]),参数是有问题的,应该使用apply,而不是call


报错已经很清楚了NodeList对象不是Array对象,它只有getter,所以没法splice方法。

要完成题主的需求,还是老老实实用replaceChild, appendChild, removeChild这些dom操作方法组合吧。

另外,call接受的平铺的参数,apply接受数组形式的参数。

[].splice.call(arr, 0, 1)
[].splice.apply(arr, [0, 1])

document.querySelectorAll 返回类数组对象,要转成数组才行,Array.prototype.slice可以转类数组对象为数组

var cols1 = Array.prototype.slice.call(cols);
[].splice.apply(cols1,[0, 1]);
【热门文章】
【热门文章】