The class array object in JavaScript (Array-like object) refers to objects that look like arrays but are not arrays. The arguments
variables and document.getElementsByTagName()
return values in JavaScript are typical class array objects.
Class Array attributes
- The class array object has one
length
property and length
The value is a non-negative integer.
- Class array objects do not have methods of array objects. For example:
push
, and pop
other methods.
Class array objects can traverse like arrays, but do not support the methods of array objects.
function test1 () { for (var i = 0; i < arguments.length;i++) { Console.log (arguments[i ]); } instanceof Array);} Test1 (2, 3); /* Output 2 3 false */function test2 () { Arguments.push ( 1);} Test2 (); /* error typeerror:undefined is not a function */
To convert a class array object to a group
slice
Method can be used to convert an array of classes (Array-like) objects into an array. You only need to call this object using the slice method on the array prototype.
function Arrayify (a) { return Array.prototype.slice.call (a);} function test3 () { var arrayified = arrayify (arguments); Arrayified.push (1); Console.log (arrayified); instanceof Array);} Test3 (2, 3); /* Output [2, 3, 1]true */
can also be used as a simple [].slice.call(a)
substitute Array.prototype.slice.call(a)
.
slice
Method can be used to convert an array of classes (Array-like) objects/collections into an array. You simply bind the method to this object. The list function in the following code arguments
is a class array object.
1 function list () {2 return Array.prototype.slice.call (arguments); 3 }45var// [1, 2, 3]
In addition to using &NBSP; Array.prototype.slice.call (
arguments
)
, you can also simply use []. Slice.call (arguments)
instead. In addition, you can use bind
to simplify the process.
1 var unboundslice = Array.prototype.slice; 2 var slice = Function.prototype.call.bind (unboundslice); 3 4 function list () {5 return Slice (arguments); 6 }78var// [1, 2, 3]
Instance Code
Array.prototype.slice.apply (Document.queryselectorall ('. Total-con li ')). Map (item) ={ if (Item.classname = = ' Hover1 ') {this. SortField = Item.getattribute (' SortField ') this. SortType = Item.getattribute (' sorttype ') return } })
Javascript class Array (array-like) object