문제

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().

To get the max_pid variable from a RHEL kernel file, I'm using an asynchronous read.

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. Is this the intended behavior of Number(), or should I be using str.trim() on the variable before passing it to 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. I'd be shocked if there was a JavaScript engine that did not conform to this part of the spec. The call to trim() is unnecessary (but harmless).

다른 팁

Whitespace is automatically trimmed from the start and end of strings. It won't remove whitespace from the middle of a number, e.g., "12 345" (evaluates to NaN). And if there are any non-numeric characters, you'll receive NaN.

See this question for more information.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top