Array.prototype.find(polyfill)中运算符>>>(零填充右移)的用法
usage of the operator >>> (Zero-fill right shift) in Array.prototype.find (polyfill)
我正在查看这个函数 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;
任何 javascript 二进制操作中都存在隐式的 "cast to int"。所以 3.14159 >>> 0 === 3
和任何无效值,例如 'foo'
都会转换为 0
为什么 >>>
而不是 >>
或 |
?显然他们期待 巨大 数组(但不是太大):
Math.pow(2,31)>>0
-2147483648
Math.pow(2,31)>>>0
2147483648
x >>> 0
强制 x
成为整数。因此,如果 list
是一个数组,那么 length
就是它的长度;但是如果 .length
不存在,或者是像 {a: 17, length: "Unicorns"}
这样愚蠢的东西,length
将是 0
.
我正在查看这个函数 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;
任何 javascript 二进制操作中都存在隐式的 "cast to int"。所以 3.14159 >>> 0 === 3
和任何无效值,例如 'foo'
都会转换为 0
为什么 >>>
而不是 >>
或 |
?显然他们期待 巨大 数组(但不是太大):
Math.pow(2,31)>>0
-2147483648
Math.pow(2,31)>>>0
2147483648
x >>> 0
强制 x
成为整数。因此,如果 list
是一个数组,那么 length
就是它的长度;但是如果 .length
不存在,或者是像 {a: 17, length: "Unicorns"}
这样愚蠢的东西,length
将是 0
.