~~ vs parseInt? [英] ~~ vs parseInt?

查看:37
本文介绍了~~ vs parseInt?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
什么是双波浪号"?(~~)JavaScript中的运算符?

D3教程提供了产生随机序列的功能:

The D3 tutorial gives a function that produces a random sequence:

var t = 1297110663, // start time (seconds since epoch)
    v = 70, // start value (subscribers)
    data = d3.range(33).map(next); // starting dataset

function next() {
  return {
    time: ++t,
    value: v = ~~Math.max(10, Math.min(90, v + 10 * (Math.random() - .5)))
  };
}

请注意以下内容中的~~(tilda tilda)

Note the ~~ (tilda tilda) in:

    value: v = ~~Math.max(10, Math.min(90, v + 10 * (Math.random() - .5)))

通过在javascript终端中玩耍,我看到:

From playing around in the javascript terminal, I see:

~~1
1
~~-1
-1
~~-1.3
-1
parseInt(5)
5
parseInt(-5)
-5
parseInt(-5.3)
-5
parseInt(5.3)
5

由于~~和parseInt似乎是等效的,所以使用parseInt的原理是什么?

Since ~~ and parseInt seem to be equivalent, whats the rationale for using parseInt?

推荐答案

它们不相同.

  • parseInt()将字符串转换为数字,读取并忽略第一个非整数字符,还可能执行基数转换(例如,将字符串解释为八进制或十六进制).
  • li>
  • parseInt() turns strings into numbers, reading up to and ignoring the first non-integer character, and also possibly performing base conversion (e.g. interpreting a string as octal, or hexadecimal).

console.log(



  parseInt(011)           +'\n'+ // 9
  parseInt('011')         +'\n'+ // 11
  parseInt('42 cats')     +'\n'+ // 42
  parseInt('0xcafebabe')  +'\n'+ // 3405691582
  parseInt('deadbeef',16) +'\n'+ // 3735928559
  parseInt('deadbeef',36) +'\n'  // 1049836114599



);

  • var x = ~~ y; 是一个技巧",与 var x = y<<0; —(ab)使用一元按位NOT运算符强制结果在带符号的32位整数范围内,并丢弃所有非整数部分.
  • var x = ~~y; is a 'trick'—similar to var x = y << 0;—that (ab)uses the unary bitwise NOT operator to force the result to be in the range of a signed 32-bit integer, discarding any non-integer portion.

console.log(



  parseInt(011)                +'\n'+// 9
  parseInt('011')              +'\n'+// 11
  parseInt('42 cats')          +'\n'+// 42
  parseInt('0xcafebabe')       +'\n'+// 3405691582
  parseInt('deadbeef',16)      +'\n'+// 3735928559
  parseInt('deadbeef',36)      +'\n' // 1049836114599



);

经常使用 ~~ x 是因为:

  1. 通常比调用方法要快.
  2. 打字比其他任何东西都要快.
  3. 它使高级用户感到很酷,因为它有点难以理解,也很合理.:)

cafebabe 测试中看到,数字大于2 31   - 1(  2,147,483,647 )或低于  - 2 31
(  −2,147,483,648 )由于有符号32位整数的限制而将环绕".

As seen in the cafebabe test, numbers above 231  -1 (  2,147,483,647  ) or below  -231
(  −2,147,483,648  ) will "wrap around" due to the limits of a signed 32-bit integer.

这篇关于~~ vs parseInt?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆