将数组原型函数与非数组一起使用

将数组原型函数与非数组一起使用

本文介绍了将数组原型函数与非数组一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们知道,我们可以使用具有函数自变量的数组原型方法,如下所示.

As we know we can use Array prototype methods with function arguments just like below.

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 推入,这给了我一个错误无法设置只有吸气剂的[object Object]的属性长度".

So like wise I tried to use push on DOM element classList like below which gives me an error "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()方法.

Note: I have just tried to learn concepts so that's why I used push even it has builtin add() method.

所以我的问题是:

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

On which objects we can use Array.prototype methods?

谢谢.

推荐答案

Array.prototype方法是适用于所有对象的通用方法.它们只是获取和设置索引属性以及调用它们的对象的.length. (并且,对于ES6,如果需要创建新实例,请使用Array实例的.constructor属性).您可以查看规范,以了解什么push确实可以.

Array.prototype methods are quite generic methods that work on all kinds of objects. They're just getting and setting indexed properties and the .length of the object they are called on. (And, with ES6, the .constructor property of Array instances if they need to create a new instance). You can check the spec to see what push does exactly.

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

So basically, to answer your question…

…在所有对象上.也就是说,在操作对象时不会引发异常的对象.请注意,push本身不会引发错误.

…on all objects. That is, objects that don't throw exceptions when they are being operated on. Notice that push itself does not throw the error.

一些例子:

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对象非常类似于x. classList非常类似于y.

The arguments object is very much like x. The classList is very much like y.

这篇关于将数组原型函数与非数组一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 18:25