if (!Array.prototype.map) {
Array.prototype.map = function(callback, thisArg) {
var T, A, k;
if (this == null) {
throw new TypeError(" this is null or not defined");
}
var O = Object(this);
var len = O.length >>> 0;
// 3.如果callback不是函数,则抛出TypeError异常.
if (Object.prototype.toString.call(callback) != "[object Function]") {
throw new TypeError(callback + " is not a function");
}
if (thisArg) {
T = thisArg;
}
A = new Array(len);
k = 0;
while(k < len) {
var kValue, mappedValue;
if (k in O) {
kValue = O[ k ];
mappedValue = callback.call(T, kValue, k, O);
A[ k ] = mappedValue;
}
k++;
}
return A;
};
}
var len = O.length >>> 0; What is the purpose of the bit operators here
过去多啦不再A梦2017-05-18 10:59:55
Personal understanding:
Because although this map method is on the prototype of Array, when it is actually called, this is not necessarily of Array type, and the length cannot be guaranteed. After adding bit operations, the uncertain value can be converted into Number.
1 >>> 0 // 1
undefined >>> 0 // 0
null >>> 0 // 0
'string' >>> 0 // 0
天蓬老师2017-05-18 10:59:55
All non-numeric values are converted to 0
All numbers greater than or equal to 0 take the integer part