admin管理员组

文章数量:1193774

1 + undefined = ?  
  1. first, String(undefined) get string "undefined"
  2. second, 1 + "undefined" = "1undefined"

what's wrong?

I run it in chrome console ,it return NaN.

can you pls explain the result?

I think it should be "1undefined". tks

1 + undefined = ?  
  1. first, String(undefined) get string "undefined"
  2. second, 1 + "undefined" = "1undefined"

what's wrong?

I run it in chrome console ,it return NaN.

can you pls explain the result?

I think it should be "1undefined". tks

Share Improve this question edited Nov 24, 2013 at 1:41 PeeHaa 72.6k60 gold badges194 silver badges264 bronze badges asked Feb 20, 2013 at 10:28 loopinglooping 1,1613 gold badges11 silver badges20 bronze badges 7
  • It's not clear to me what you mean. Can you show in code which result returns what? – Pekka Commented Feb 20, 2013 at 10:30
  • Why don't you try it? – gaborsch Commented Feb 20, 2013 at 10:31
  • 2 Here: es5.github.com/#x11.6.1. – Felix Kling Commented Feb 20, 2013 at 10:31
  • 2 To elaborate, neither 1 nor undefined are strings, so they're coerced to numbers. Number(undefined) is NaN, and 1 + NaN is still NaN. – Frédéric Hamidi Commented Feb 20, 2013 at 10:33
  • 1 Why do you think undefined gets converted to a string? It doesn't. – Felix Kling Commented Feb 20, 2013 at 10:34
 |  Show 2 more comments

4 Answers 4

Reset to default 18

NaN is the result of a failed Number operation.

1 + undefined           // NaN
"1" + undefined         // "1undefined"
1 + "" + undefined      // "1undefined"
1 + ("" + undefined)    // "1undefined"
typeof NaN              // "number"
typeof undefined        // "undefined"
NaN === NaN             // false (it's not reflexive!)
undefined === undefined // true (it's reflexive)
NaN.toString()          // "NaN"

NaN means Not a Number where a number was expected. Any Number operation with NaN will result in NaN as well.

You expect a string concatenation, but this will only happen if you have at least one string. And in your example nothing is a string. 1 is not a string and undefined is not a string.

1 + undefined = NaN

When you do 1 + "undefined" you concatinate the 1 to the String "undefined" resulting in the string "1undefined"

undefined is nothing or like Null in other languages (variable is not set)

In Javascript null is an expected absense (set to null somewhere) of a value and undefined is an unexpected absense of a value (never set)

What do you want to accomplish?

var charsLeft = 35 - (currentWord?.length ?? 0)

Thought that this code would come handy to someone.

本文标签: javascriptwhat39s the result of 1undefinedStack Overflow