亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

為什麼999.222<<0 會得到整數999 ? javascript

為什麼999.222<<0 會得到整數999 ? javascript

哈士奇WWW 2018-09-11 13:38:10
利用這段代碼color = "#"+ (Math.random()*0xffffff<<0).toString(16);實現了隨機得到顏色但是實在不明白為什麼?這裡有解釋到一點 但也不明白http://www.cnblogs.com/rubylo...基本實現4的改進,利用左移運算符把0xffffff轉化為整型。這樣就不用記16777215了。由于左移運算符的優先級比不上乘號,因此隨機后再左移,連Math.floor也不用了。如果x.abcd << 0 這樣也可以得到整數 x ,那又和Math.floor(x.abcd) 有什麼差別呢?
查看完整描述

1 回答

?
肥皂起泡泡

TA貢獻1829條經驗 獲得超6個贊

這種問題,看規范就知道啦

移位運算在內部是啥樣的?

12.8.3.1 Runtime Semantics: Evaluation

ShiftExpression : ShiftExpression << AdditiveExpression

  1. Let lref be the result of evaluating ShiftExpression.

  2. Let lval be GetValue(lref).

  3. ReturnIfAbrupt(lval).

  4. Let rref be the result of evaluating AdditiveExpression.

  5. Let rval be GetValue(rref).

  6. ReturnIfAbrupt(rval).

  7. Let lnum be ToInt32(lval).

  8. ReturnIfAbrupt(lnum).

  9. Let rnum be ToUint32(rval).

  10. ReturnIfAbrupt(rnum).

  11. Let shiftCount be the result of masking out all but the least significant 5 bits of rnum, that is, compute rnum & 0x1F.

  12. Return the result of left shifting lnum by shiftCount bits. The result is a signed 32-bit integer.

關鍵就是我標紅的那一步,這一步會把變量lvalToInt32的運算,而這個lval就是來自我們移位運算的左值,就是你的999.222。

接下來,再來看看ToInt32做了啥:

7.1.5 ToInt32 ( argument )

The abstract operation ToInt32 converts argument to one of 2^32 integer values in the range ?2^31 through 2^31?1, inclusive. This abstract operation functions as follows:

  1. Let number be ToNumber(argument).

  2. ReturnIfAbrupt(number).

  3. If number is NaN, +0, ?0, +∞, or ?∞, return +0.

  4. Let int be the mathematical value that is the same sign as number and whose magnitude is floor(abs(number)).

  5. Let int32bit be int modulo 2^32.

  6. If int32bit ≥ 2^31, return int32bit ? 2^32, otherwise return int32bit.

關鍵的那步我也給你標出來了,這里會把輸入值直接取整。
所以,給一個浮點數做0的移位運算,結果就是取整。

對于Math.floor,規范沒說具體實現,只給了一句話——

Returns the greatest (closest to +∞) Number value that is not greater than x and is equal to a mathematical integer. If x is already an integer, the result is x.
返回不大于x的最大整數;假如x已經是整數了,那么返回x。

Math.floor的實現沒給出,但是移位取整中間還多了好幾個步驟,除了寫代碼的時候能稍微簡潔一點以外,我覺得還是Math.floor更好點。

另外,ToInt32里面的那個floor運算是這么實現的:

floor(x) = x?(x modulo 1)

modulo是取模運算的意思,x1取模,那就是求x的小數部分,隨后x剪掉了自己的小數部分,那就剩下整數了嘛。

必須要注意的是,ToInt32中是先取絕對值然后再取整的,所以在負數區間內,<< 0Math.floor的結果是不一樣的。
Math.floor返回的是不大于輸入值的最大整數,那么肯定就有Math.floor(-1.5) = -2。
而對于<< 0運算,它是先取絕對值,然后取整,最后再把符號弄回去,那么就有-1.5 << 0 = -1。


查看完整回答
反對 回復 2018-10-17
  • 1 回答
  • 0 關注
  • 606 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號