gpt4 book ai didi

javascript - 奇怪的 JavaScript 运算符 : expr >>> 0

转载 作者:行者123 更新时间:2023-12-03 02:19:20 24 4
gpt4 key购买 nike

以下函数旨在实现indexOf IE 中的属性。如果您曾经不得不这样做,我相信您以前见过它。

if (!Array.prototype.indexOf){

Array.prototype.indexOf = function(elt, from){

var len = this.length >>> 0;
var from = Number(arguments[1]) || 0;

from = (from < 0)
? Math.ceil(from)
: Math.floor(from);

if (from < 0)
from += len;

for (; from < len; from++){
if (from in this &&
this[from] === elt)
return from;
}

return -1;
};
}

我想知道像作者在初始长度检查中所做的那样使用三个大于号是否常见?

var len = this.length >>> 0

在控制台中执行此操作只会返回我传递给它的对象的长度,而不是 true 或 false,这让我思考语法的目的。这是我不知道的高级 JavaScript 忍者技术吗?如果是的话,请赐教!

最佳答案

>>>Zero-fill right shift运算符(operator)。 >>> 0 是对运算符的滥用,可将任何数字表达式转换为“整数”或将非数字表达式转换为零。它的作用如下:

This operator shifts the first operand the specified number of bits to the right. Excess bits shifted off to the right are discarded. Zero bits are shifted in from the left. The sign bit becomes 0, so the result is always positive.

Here is an explanation适用于所有位运算的转换为整数行为:

Bitwise operators treat their operands as a sequence of 32 bits (zeros and ones), rather than as decimal, hexadecimal, or octal numbers. [...] Bitwise operators perform their operations on such binary representations, but they return standard JavaScript numerical values.

这些语句共同断言 expr >>> 0 将始终返回正数,如下所示:

  1. expr 转换为 32 位整数以进行按位运算
  2. >>> 0 无效(没有位移动)
  3. 结果转换为 Number

以下是一些表达式及其结果:

        1 >>> 0 // 1 -- Number cast to 32-bit integer then back to Number
"1" >>> 0 // 1 -- String cast to 32-bit integer then back to Number
undefined >>> 0 // 0 -- failed cast yields zero

其他有趣的案例:

      1.1 >>> 0 // 1          -- decimal portion gets it
-1 >>> 0 // 4294967295 -- -1 = 0xFFFFFFFF
// Number(0xFFFFFFFF) = 4294967295
"A" >>> 0 // 0 -- cast failed
"1e2" >>> 0 // 100 -- 1x10^2 is 100
"1e10" >>> 0 // 1410065408 -- 1x10^10 is 10000000000
// 10000000000 is 0x00000002540BE400
// 32 bits of that number is 0x540BE400
// Number(0x540BE400) is 1410065408

注意:您会注意到它们都没有返回 NaN .

关于javascript - 奇怪的 JavaScript 运算符 : expr >>> 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5747123/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com