最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Why ~-(2 + "2") is 21? - Stack Overflow

programmeradmin2浏览0评论

I saw this question in a test, but I don't understand how operators work on the statement.

let a = ~-(2 + "2");
console.log(a);

I saw this question in a test, but I don't understand how operators work on the statement.

let a = ~-(2 + "2");
console.log(a);

Share Improve this question asked Feb 19, 2018 at 23:28 dev-ccdev-cc 4543 silver badges13 bronze badges 4
  • 1 Which part don't you understand? Break it down: 2 + "2" -> "22"; then -"22" -> -22; then ~-22 -> 21. Does this existing Q&A answer your question? If not, could you edit to be more specific about what it is? – jonrsharpe Commented Feb 19, 2018 at 23:30
  • 1 Did you try doing this a step at a time in the javascript console of your browser? Try 2 + "2" first, and so on... – lurker Commented Feb 19, 2018 at 23:31
  • simple answer, because type coercion, maths and bitwise operations - all these are documented - try mdn documentation for up to date documentation – Jaromanda X Commented Feb 19, 2018 at 23:34
  • 1 Check this out https://www.joezimjs./javascript/great-mystery-of-the-tilde/ – MaveRick Commented Feb 19, 2018 at 23:37
Add a ment  | 

2 Answers 2

Reset to default 10
~-(2 + "2")
  • 0: 2 + "2" (Concatenation) = "22"
  • 1: -"22" (Coercion) = -22
  • 2: ~-22 (Bitwise NOT) = -(-22 + 1) = 21

Bitwise NOTing any number x yields -(x + 1). For example, ~-5 yields 4.

  • Step 1: (2+"2") results in the string "22"
  • Step 2: -("22") is the same as (-1)*("22"), and results in the number -22
  • Step 3: Bitwise not (~), which results in 21

To understand that last step, you need to know that JavaScript stores numbers as 64-bit floating point numbers, but all bitwise operations are performed on 32-bit signed integers using 2's pliment.

So:

  • -22 representation is the 2's pliment of +22
  • +22 in binary = 0000 0000 0000 0000 0000 0000 0001 0110
  • 2's pliment of (22) = (-22) = 1111 1111 1111 1111 1111 1111 1110 1001
    • 1 = 1111 1111 1111 1111 1111 1111 1110 1010
  • ~-22 = bitwise not of -22 = 0000 0000 0000 0000 0000 0000 0001 0101
  • 10101 in binary = 21 in decimal
发布评论

评论列表(0)

  1. 暂无评论