JavaScript将字符串转换为整数有哪些方法,哪种最快
三叔
三叔 2017-07-05 10:41:53
[JavaScript讨论组]

有哪些方法。哪种方法最快!
Number()
parseInt()

三叔
三叔

全部回复(8)
伊谢尔伦

(非官方)测试结果,自己看

Number()

parseInt()

Math.floor()

Math.round()

Math.ceil()

|0

^0

-0

Math.floor+

-Math.floor-

--split[0]

+split[0]

大家讲道理

+'123'

仅有的幸福
Math.floor(+'123.123');

-Math.floor(-'123.123')

-(-'123.213'.split('.')[0]);

+'123.213'.split('.')[0]

转换方式多了去,不过都是使用运算符进行隐式转换的小技巧。

除了优先级和结合性,还要注意不同的操作数会对运算符的隐式转换造成影响。

巴扎黑

补充下还有这些方法,
'3.1425' | 0
'7.86'^0
'123'-0

感觉应该是哪些专门用于转化的方法比较快吧,像你说的parseInt、Number这些吧。快慢没有亲自试过唉

三叔

var a = 1.123445;
a >> 0;

三叔

String inString = ""; // The inString variable is used to store the value from the input

Void setup () {
  // Open serial port with baudrate 9600
  Serial.begin (9600);
  While (! Serial) {
    ; // wait Serial port is turned on (just with Arduino Leonardo circuit)
  }

  // Send a message that the setup function has finished
  Serial.println (" n nChanges compared to:");
  Serial.println ();
}

Void loop () {
  // Read the value from Serial
  While (Serial.available ()> 0) {
    Int inChar = Serial.read ();
    If (isDigit (inChar)) {// Check function NUMBER is a digital character
      // and add strings. Otherwise you will add an integer to it: P
      InString + = (char) inChar;
    }
    // If inChar is a newline character. I print the results
    If (inChar == ' n') {// One character uses '(single quote) and one string to use' (double quotes)
      Serial.print ("value:");
      Serial.println (inString.toInt ());
      Serial.print ("string:");
      Serial.println (inString);
      // delete the value of the inString variable
      InString = "";
    }
  }
}
photo editor

滿天的星座

还有~~'123.45'

滿天的星座

var a = '1'

var b = a * 1

b 为number

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号