Slice can be used to obtain array fragments. It returns a new array without modifying the original array. In addition to normal usage, slice is often used to convert an array-like object to a true array.
Glossary: array-like object-objects with the length attribute, such as {0: 'foo', length: 1}, or even {length: 'bar '}. the most common array-like objects are arguments and NodeList.
View the source code of the V8 engine array. js to simplify the internal implementation of slice:
The Code is as follows:
Function slice (start, end ){
Var len = ToUint32 (this. length), result = [];
For (var I = start; I <end; I ++ ){
Result. push (this [I]);
}
Return result;
}
We can see that slice does not need this to be of the array type, but only needs to have the length attribute. And the length attribute can not be of the number type. If the value cannot be converted, ToUnit32 (this. length) returns 0.
For standard browsers, the slice principle has been clearly explained above. But the annoying ie is always a mess for us:
The Code is as follows:
Var slice = Array. prototype. slice;
Slice. call (); // => IE: Object expected.
Slice. call (document. childNodes); // => IE: JScript object expected.
The above code reports an error in ie. The hateful IE Trident engine is not open-source, so we only have to guess:
The Code is as follows:
Function ie_slice (start, end ){
Var len = ToUint32 (this. length), result = [];
If (_ typeof _ this! = 'Jscript object') throw'jscript Object expected ';
If (this = null) throw 'objectexpected ';
For (var I = start; I <end; I ++ ){
Result. push (this [I]);
}
Return result;
}
So far, we have fully completed the Compact ie.
There is another topic about slice: using Array. prototype. slice or []. slice? Theoretically, [] an Array needs to be created, which is slightly inferior to Array. prototype. But in fact, the two are similar, just like using I ++ or ++ I in a loop, which is purely a personal habit.
The last topic is about performance. For array filtering, there is a way to sacrifice the color:
The Code is as follows:
Var ret = [];
For (var I = start, j = 0; I <end; I ++ ){
Ret [j ++] = arr [I];
}
Use space to change the time. Remove push. For large arrays, the performance improvement is obvious.
I am in a bad mood when I write blogs early in the morning. I have to leave a question for you:
The Code is as follows:
Var slice = Array. prototype. slice;
Alert (slice. call ({0: 'foo', length: 'bar'}) [0]); //?
Alert (slice. call (NaN). length );//?
Alert (slice. call ({0: 'foo', length: '000000'}) [0]); //?