对非数组使用数组原型函数

Use Array Prototype Functions with non-arrays

正如我们所知,我们可以使用带有函数 arguments 的数组原型方法,如下所示。

function abc() {
   // As 'arguments' is a array like object which don't have Array prototype functions.
   Array.prototype.push.call(arguments, 30);
   console.log(arguments);
}
abc(10, 20);   // Output is: [10, 20, 30]

所以我同样尝试在 DOM 元素 classList 上使用推送,如下所示,这给了我一个错误 "Cannot set property length of [object Object] which has only a getter".

var bodyClassList = document.body.classList;
Array.prototype.push.call(bodyClassList, 'myClass');

注意:我刚刚尝试学习概念,所以这就是我使用 push 的原因,即使它有内置的 add() 方法。

所以我的问题是:

我们可以在哪些对象上使用 Array.prototype 方法?

提前致谢。

Array.prototype 方法是非常通用的方法,适用于所有类型的对象。他们只是获取和设置索引属性以及调用它们的对象的 .length。 (并且,对于 ES6,Array 个实例中的 .constructor 属性 个,如果它们需要创建一个新实例)。您可以 check the spec 查看 push 的具体作用。

所以基本上,回答你的问题......

On which objects we can use Array.prototype methods?

…在所有对象上。也就是说,对象在被操作时不会抛出异常。请注意 push 本身不会抛出错误。

一些示例:

var x = {0:0, length:1};
Array.prototype.push.call(x, 1);
console.log(x); // {0:0, 1:1, length:2}
console.log(Array.prototype.slice.call(x)); // [0, 1]
var y = {0:0, get length() { throw new Error("boo!"); }}
Array.prototype.push.call(y, 1); // throws
var z = {get 0() { throw new Error("boo!"); }, length: 1};
Array.prototype.push.call(z, 1);
console.log(z); // {0:…, 1:1, length:2}
console.log(Array.prototype.slice.call(z)); // throws

arguments 对象非常像 xclassList 非常像 y