简体   繁体   English

JavaScript:Number()的预期行为

[英]JavaScript: Intended behavior of Number()

I'm currently reading string integers from files and passing them to functions. 我正在从文件中读取字符串整数并将它们传递给函数。 Since most files have a trailing line feed, I was wondering about the behavior of Number() . 由于大多数文件都有尾随换行符,我想知道Number()的行为。

To get the max_pid variable from a RHEL kernel file, I'm using an asynchronous read. 要从RHEL内核文件获取max_pid变量,我正在使用异步读取。

var options = {
  encoding: 'utf8'
};

fs.readFile('/proc/sys/kernel/pid_max', options, function (err, data) {
  var max_pid = Number(data);

  // or trim the string first
  var max_pid = Number(data.trim());
});

The variable data for my system returned the string '32768\\n' , and using Number() on that string strips the line feed. 我系统的可变data返回字符串'32768\\n' ,并在该字符串上使用Number()删除换行符。 Is this the intended behavior of Number() , or should I be using str.trim() on the variable before passing it to Number() ? 这是Number()的预期行为,还是应该在将变量传递给Number()之前对变量使用str.trim() Number()

I ask this for reasons of consistency across environments, as well as proper use of functions. 我问这是出于各种环境的一致性以及正确使用功能的原因。

According to Section 9.3.1 of the ECMAScript specification , conversion of a string to a number will automatically strip leading and trailing white space. 根据ECMAScript规范的第9.3.1节,将字符串转换为数字将自动去除前导和尾随空格。 I'd be shocked if there was a JavaScript engine that did not conform to this part of the spec. 如果有一个JavaScript引擎不符合规范的这一部分,我会感到震惊。 The call to trim() is unnecessary (but harmless). 调用trim()是不必要的(但无害)。

Whitespace is automatically trimmed from the start and end of strings. 从字符串的开头和结尾自动修剪空白。 It won't remove whitespace from the middle of a number, eg, "12 345" (evaluates to NaN ). 它不会从数字的中间删除空格,例如"12 345" (评估为NaN )。 And if there are any non-numeric characters, you'll receive NaN . 如果有任何非数字字符,您将收到NaN

See this question for more information. 有关更多信息,请参阅此问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM