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

1.toString() SyntaxError in Javascript - Stack Overflow

programmeradmin4浏览0评论

Why the first line below gives error although the second and third lines work fine?

1.toString(); // SyntaxError
(1).toString(); // OK
1['toString'](); // OK

Why the first line below gives error although the second and third lines work fine?

1.toString(); // SyntaxError
(1).toString(); // OK
1['toString'](); // OK
Share Improve this question asked Oct 3, 2012 at 3:45 scusyxxscusyxx 1,2441 gold badge8 silver badges9 bronze badges 2
  • 1 And "they" want to make javascript strictly typed! – RobG Commented Oct 3, 2012 at 3:57
  • Don't worry about him. The specification authors are making it strictly typed. – Amir Rahnama Commented Nov 12, 2015 at 8:56
Add a ment  | 

4 Answers 4

Reset to default 12

The . presents ambiguity. Is it a decimal, or a property accessor?

The interpreter sees it as a decimal, so you can use .. to allow both the decimal, then the property syntax.

1..toString();

Or use one of the other ways you show to resolve the ambiguity.

The parser is trying to treat 1. as the start of a floating-point literal -- only toString turns it into an invalid number.

Compare with:

1.0.toString()

In (1).toString(), (1) forces it to evaluate before .toString() so it works. In 1.toString(), 1 is not a valid identifier so it does not work.

In Javascript, using the dot (.) can be interpreted in one of two ways:

  1. As a Property Accessor (e.g., var prop = myObject.prop;).
  2. As part of a Floating-point Literal (e.g. var num = 1.5;).

In the above case, the leading 1. in 1.toString() is interpreted as a floating point number, hence the error:

SyntaxError: identifier starts immediately after numeric literal (learn more)

This is the same error you get if you try and declare a variable that starts with a number: var 1person = 'john';

To prevent the interpreter from seeing the 1. as a decimal and instead see it as accessing a property on our literal 1, there are several ways to acplish this:

// Via white-space after the numeric literal
1 .toString();

1
.toString();

// Via a grouping-operator, aka, parentheses
// @see https://developer.mozilla/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#Grouping_operator
(1).toString();

// Via an additional dot. Made clearer with parentheses as `(1.).toString()`
1..toString();

// Via an explicit fractional part (because `1. === 1.0`)
1.0.toString();

// Via bracket notation
1['toString']();
1.['toString']();
1.0['toString']();
发布评论

评论列表(0)

  1. 暂无评论