我正在查看这个函数Array.prototype.find
从(mdn polyfill):
if (!Array.prototype.find) {
Array.prototype.find = function(predicate) {
if (this == null) {
throw new TypeError('Array.prototype.find called on null or undefined');
}
if (typeof predicate !== 'function') {
throw new TypeError('predicate must be a function');
}
var list = Object(this);
var length = list.length >>> 0;
var thisArg = arguments[1];
var value;
for (var i = 0; i < length; i++) {
value = list[i];
if (predicate.call(thisArg, value, i, list)) {
return value;
}
}
return undefined;
};
}
我不明白这段代码的目的:
var length = list.length >>> 0;
x >>> 0
强制x
变为整数。因此,如果list
是一个数组,则length
为其长度;但是如果.length
不存在,或者是像{a: 17, length: "Unicorns"}
这样愚蠢的东西,length
将是0
。
在任何javascript二进制操作中都存在隐式的"转换为int"。因此,3.14159 >>> 0 === 3
和任何无效值,如'foo'
,都被强制转换为0
为什么是>>>
而不是>>
或|
?显然,他们期望巨大的数组(但不是太大):
Math.pow(2,31)>>0
-2147483648
Math.pow(2,31)>>>0
2147483648