Problem description
In everyday coding, you will encounter the problem of converting class array objects to arrays, one of the most common ways to use the Array.prototype.slice () method.
Class Array Object
So-called class array objects, JavaScript defines them as: they look like arrays, they have only the same parts and arrays:
- Have the Length property
- element is saved in the object and can be accessed by index
But there are no other methods of arrays, such as push, slice, indexof, and so on.
Conversion process
For example:
var foo = { 0: 'Java', 1: 'Python', 2: 'JavaScript', length: 3};// 因为foo对象本身并没有slice方法,所以通过call调用var arr = Array.prototype.slice.call(foo); // [‘Java’,’Python’,’JavaScript’]
So the question is, why is the slice method able to convert an object to an array? The simplest way is to look at the source code implementation.
Source Code Implementation
You can view the array internal method implementation in the V8 engine
function Arrayslice (start, end) {check_object_coercible (this, "Array.prototype.slice"); var Array = To_ OBJECT (this); var len = to_length (array.length); var start_i = To_integer (start); var end_i = len; if (!is_undefined (end)) End_i = To_integer (end); if (Start_i < 0) {start_i + = Len; if (start_i < 0) start_i = 0;} else {if (Start_i > len) start_i = len;} if (End_i < 0) {end_i + = Len; if (End_i < 0) end_i = 0;} else {if (End_i > len) end_i = len;} var result = Arrayspeciescreate (array, maxsimple (end_i-start_i, 0)); First, convert the array if (End_i < start_i) return result; If there are no arguments, return the array directly if (usesparsevariant (array, Len, Is_array (array), end_i-start_i)) {%normalizeelements (array); if (IS _array (Result))%normalizeelements (result); Sparseslice (Array, start_i, end_i-start_i, Len, result); } else {Simpleslice (array, start_i, end_i-start_i, Len, result);} result.length = End_i-start_i; return result; }
As can be seen from the above code, when there is no input parameter, a new array is created, then all the elements of the current array are thrown in, and finally the new array is returned.
Reference
The array implementation of the V8
The "front-end Basic Series" Slice method converts an array of classes into an array implementation principle