one of them
var O = Object(this);
var len = O.length >>> 0;
What do these two sentences mean?
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(searchElement, fromIndex) {
var k;
if (this == null) {
throw new TypeError('"this" is null or not defined');
}
var O = Object(this);
var len = O.length >>> 0;
if (len === 0) {
return -1;
}
var n = +fromIndex || 0;
if (Math.abs(n) === Infinity) {
n = 0;
}
if (n >= len) {
return -1;
}
k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
while (k < len) {
if (k in O && O[k] === searchElement) {
return k;
}
k++;
}
return -1;
};
}
Object(this) is not to create a new object, but to convert this into an Object. It is naturally useless for objects that are Objects themselves, such as Array and Object.
O.length >>> 0
The three greater-than signs here do not mean that it is always greater than or equal to 0, but a bit operator of JS, which represents an unsigned displacement. The following 0 represents a displacement of 0 bits, but Before JS performs unsigned displacement, it will be converted into an unsigned 32-bit integer for calculation, so>>>0
means convertingO.length
into a positive integer.Why do we need these two steps? Isn’t JS’s Array already an Object? Isn't array.length itself definitely a non-negative integer? That’s because this function is a universal function and can be called by non-Array using call. For example:
The "abc" here is this in the function body. It is a basic type and needs to be packaged into an Object to use the following in syntax.
We can use the Array.prototype.indexOf method not only on the basic type, but also on a non-Array Object. At this time, the length is specified by ourselves and cannot be guaranteed to be a positive integer, so it needs to be converted to a non-Array value inside the function. Negative integer.