最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Any arithmatic operation with NaN should be a NaN - Stack Overflow

programmeradmin9浏览0评论

I am having a statement like

var x = parseInt(1)+'b';

why this result is 1b but isNAN('b') is returning true; so result should be NaN?

I am having a statement like

var x = parseInt(1)+'b';

why this result is 1b but isNAN('b') is returning true; so result should be NaN?

Share Improve this question edited Jan 10, 2017 at 17:16 Suren Srapyan 68.7k14 gold badges125 silver badges117 bronze badges asked Jan 10, 2017 at 17:15 Atul KumarAtul Kumar 831 silver badge6 bronze badges 2
  • 1 You got the answers already but also check the Documentation on Expressions and operators - String Operators – Nope Commented Jan 10, 2017 at 17:19
  • Short answer: because it isn't an arithmetic operation :) – Álvaro González Commented Jan 10, 2017 at 17:29
Add a ment  | 

4 Answers 4

Reset to default 12

Number + String is not an arithmetic operation.

In the Number + String statement, engine will convert the number into string equivalent.

In your case it will be 1 -> '1'. And then will be simple strings concatenation, because + operator will concatenate two strings.

'1' + 'b' === '1b';

Code Snippet

console.log(1 + 'b');

In case with IsNaN('b'), it tries to detect is the parameter a number or not. 'b' is not a number (NaN), so it will return true.

Code Snippet

console.log(isNaN('b'));

For more see Documentation

Because it's not an arithmetic operation, it's a string concatenation. Whenever either operand to + is a string, string concatenation is done rather than addition; details in the spec. If the other operand isn't a string, it's convered to string. So you end up with "1" + "b" => "1b".

The + operator is defined as concatenation if either operand is a string.

Source: https://www.ecma-international/ecma-262/5.1/#sec-11.6.1

The + operator, when it has a string as one of it's arguments, will be interpreted as a "concatenation" operator instead of "addition". The non-string value will be converted to a string and appended to or prepended to the string value, depending on whether or not it is to the right or the left (respectively) of the operator.

发布评论

评论列表(0)

  1. 暂无评论