Javascript 缩短DOMRect的数组

Javascript 缩短DOMRect的数组,javascript,Javascript,如何缩短rects(例如,缩短为1) 功能测试(elID){ var rects=document.getElementById(elID.getClientRects(); 警报(rects.length);//7 rects.length=1; 警报(rects.length);//7??? } Donec tempus,nisi是一只pharetra placerat。 直视 拼接是您正在寻找的解决方案: rects = rects.splice(0,1); 拼接需要两个参数:(s

如何缩短
rects
(例如,缩短为1)


功能测试(elID){
var rects=document.getElementById(elID.getClientRects();
警报(rects.length);//7
rects.length=1;
警报(rects.length);//7???
} 
Donec tempus,nisi是一只pharetra placerat。
直视

拼接
是您正在寻找的解决方案:

rects = rects.splice(0,1);

拼接需要两个参数:(
start
deleteCount

start
是要从中删除的偏移量。JavaScript数组中的第一个偏移量是
0
,最后一个偏移量是
(rects.length-1)

deleteCount
是正向要删除的元素数。如果未包括,该功能将在给定偏移量之前拼接所有元素。

通过切片

var rects = document.getElementById(elID).getClientRects().slice(0,1);
返回
ClientRectList
ClientRectList
length
属性不可写,与之相反

属性的可写性可以使用找到。例如,尝试在控制台中运行以下命令:

var x = document.body.getClientRects();
Object.getOwnPropertyDescriptor(x.constructor.prototype, 'length');
// Yields: "Object {set: undefined, ..."
// Undefined setter
并将其与:

var x = [1, 2, 3, 4];
Object.getOwnPropertyDescriptor(x.constructor.prototype, 'length');
// Yields: "Object {value: 0, writable: true, ..."
// Writable: true. It's writable.
因此,
ClientRectList
与数组不同。那么,我们如何更改它,以便像使用数组一样使用它呢

不带参数调用将返回数组的副本。我们可以利用这个优势。(
x
保存一个
ClientRectList
):

现在,您可以像对待普通数组一样对待
x
:修改长度,调用
拼接
,调用
切片
,无论您需要做什么


快乐编码

不,一点帮助都没有。我试着按照你的建议去做,我一遍又一遍地查看文档,但它从未以这种方式删除成员。。。甚至更糟。当我实现你的代码片段时,之后的代码永远不会执行。。。和我以前试过的一样。一定会出现某种“内部错误”。哦,是的。它在工作。。。。很多。我后来想,它不是“普通数组”,所以它是完全不同的东西。我会研究一下,你在代码中做了什么…:-)ES6:不使用
Array.prototype.slice.call(ClientRectList)
可以使用转换为数组-
const RectListArray=[…ClientRectList]
var x = [1, 2, 3, 4];
Object.getOwnPropertyDescriptor(x.constructor.prototype, 'length');
// Yields: "Object {value: 0, writable: true, ..."
// Writable: true. It's writable.
x = Array.prototype.slice.call(x);
// Yields an array of ClientRects