number toString()方法返回number和variable的不同值 [英] number toString() method returns different values for number and variable

查看:106
本文介绍了number toString()方法返回number和variable的不同值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我跑

var num = 23;
var n = num.toString();
console.log(n)

它记录 23 如预期的那样,但如果我将 toString()直接应用于某个数字,

it logs 23 as expected but if I apply the toString() directly to a number like,

var n = 15.toString();
console.log(n)

它会抛出错误:

Uncaught SyntaxError: Invalid or unexpected token.

我注意到它也适用于num变量中的十进制值(如.3,.99, 2.12,99.1)等可以请一些人帮助我理解这个功能的不同之处

I noticed it also works fine for decimal values in the num variables (like .3, .99, 2.12, 99.1) etc. Could some one please help me understand the difference and how this function works

推荐答案

JavaScript解析工作如下意。您声明了以下内容:

JavaScript parsing is working as intended. You have declared the following:

23.toString()

我们认为这是整数,其上调用了一个函数。

We see this as an Integer with a function being called on it.

解析器没有。解析器看到尝试声明浮点文字。解析器使用:

The parser doesn't. The parser sees an attempt to declare a floating-point literal. The parser uses this:

[(+ | - )] [digits] [.dits] [(E | e)[(+ | - )]数字]

它假定您声明 Floating-Point Literal 因为它是:

It assumes that you are declaring a Floating-Point Literal because it is:


  • 不是变量,因为它不以字母或可接受的字符开头

  • 是一个数字文字,因为它以数字字符开头

  • 是一个浮点数,因为它有一个小数点。

如果你真的,出于所有意图和目的,想要调用 23.toString(),行动方案是隔离文字,如下所示:

If you really, for all intents and purposes, want to call 23.toString(), the course of action is to isolate the literal like so:

(23).toString(); //interprets 23 as literal

23..toString(); //interprets 23. as literal

话虽如此,JavaScript足够灵活,知道你想要使用在大多数情况下,23作为字符串。这个编译得很好。

That being said, JavaScript is flexible enough to know you want to use 23 as a String in most cases. This compiles fine.

var foo = "The answer is " + 42;  

这样做。

var bar = "39" - 0 + 3; //42

这不是。

var baz = "39" + 3; //393!!! 

这篇关于number toString()方法返回number和variable的不同值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆