What does ~~ (“double tilde”) do in Javascript?

前端 未结 9 730
有刺的猬
有刺的猬 2020-11-22 17:16

I was checking out an online game physics library today and came across the ~~ operator. I know a single ~ is a bitwise NOT, would that make ~~ a NOT of a NOT, which would

9条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-22 17:42

    Converting Strings to Numbers

    console.log(~~-1);    // -1
    console.log(~~0);     // 0
    console.log(~~1);     // 1
    console.log(~~"-1");  // -1
    console.log(~~"0");   // 0
    console.log(~~"1");   // 1
    console.log(~~true);  // 1
    console.log(~~false); // 0
    

    ~-1 is 0

    if (~someStr.indexOf("a")) {
      // Found it
    } else  {
      // Not Found
    }
    

    source

提交回复
热议问题