In addition to normal usage, slice is often used to convert a Array-like object to a true array.
Noun Explanation: array-like object– has the length attribute object, such as {0: ' foo ', length:1}, or even {length: ' Bar '}. The most common array-like objects are arguments and nodelist.
To view the source code of the V8 engine array.js, you can simplify the internal implementation of slice to:
Copy Code code 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;
}
As you can see, slice does not need this as the array type, only the length attribute is required. And the length property can be not a number type, and ToUnit32 (this.length) returns 0 when it cannot be converted to a numeric value.
For standard browsers, the slice principle has been explained clearly. But annoying ie, always give us the chaos:
Copy Code code as follows:
var slice = Array.prototype.slice;
Slice.call (); => Ie:object expected.
Slice.call (Document.childnodes); => Ie:jscript object expected.
The above code, in IE, the error. Hateful IE's Trident engine is not open source, then we have to guess:
Copy Code code 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 ' oject expected ';
for (var i = start, I < end; i++) {
Result.push (This[i]);
}
return result;
}
At this point, the wretched IE to justify the completion.
On slice, there is also a topic: with Array.prototype.slice or [].slice? Theoretically, [] you need to create an array that is slightly less performance than Array.prototype. But in fact, the two are similar, as in the cycle of i++ or ++i, the same as personal habits.
Last topic, about performance. For array filtering, there is a sacrificial hue:
Copy Code code as follows:
var ret = [];
for (var i = start, j = 0; i < end; i++) {
Ret[j++] = Arr[i];
}
Use space to change time. Remove push, for large arrays, performance improvement is more obvious.
Early in the morning to write Bo, the mood is not very good, you have to leave a topic for everyone:
Copy Code code 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: ' 100 '}) [0]); // ?