在JavaScript中使用toString [英] Usage of toString in JavaScript

查看:96
本文介绍了在JavaScript中使用toString的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读Douglas Crockford的 JavaScript :好的部件 ,我正处于定义淡入淡出功能的位置。部分代码归结为:

I'm reading through Douglas Crockford's JavaScript: The Good Parts, and I'm at the point where he defines a fade function. Part of this code boils down to this:

var level = 1;
var hex = level.toString(16);

所以我在浏览器的控制台中运行它以查看我得到的内容....

So I run this in my browser's console to see what I get....

var level = 1;
level.toString(16);

嘿,它返回 1 。 .. Fabuloso! Wunderbar!

Hey, it returns "1"... Fabuloso! Wunderbar!

然后为了厚颜无耻,我试着看看我得到了什么...

Then to be cheeky, I try this to see what I get...

1.toString(16);

我得到


SyntaxError:意外的令牌ILLEGAL

SyntaxError: Unexpected token ILLEGAL

什么是什么?如果 level 是一个等于1的变量,并且在该级别上运行此方法工作正常,那么为什么不在实际的数字1上运行此方法呢?我尝试使用 toPrecision()方法进行类似的实验,在两种情况下都能正常工作。这是什么问题?这是JavaScript实现中的另一个固有缺陷,还是我错过了什么?我正在Google Chrome中进行测试。

What the what? If level is a variable equal to 1, and running this method on level works fine, then why doesn't running this method on the actual number 1 work? I tried a similar experiment with the toPrecision() method and that worked fine in both cases. What's the issue here? Is this another one of those inherent flaws in the JavaScript implementation, or am I missing something? I am testing in Google Chrome.

相关:Stack Overflow问题 为什么要穿数字文字是否可以访问数字方法?

Related: Stack Overflow question Why don't number literals have access to Number methods?.

推荐答案

这只是一种语言语法限制。

It's just a language grammar limitation.

由于 1。是合法的文字编号( 1.t 不是)令牌器会将其拆分为以下令牌:

Since 1. is a legal literal number (and 1.t is not) the tokeniser will split this into the following tokens:

1.
toString
(
)

这是一个非法的序列令牌。它是对象方法,而不是对象。方法

And that's an illegal sequence of tokens. It's object method, instead of object . method.

在@ Joey的答案的工作版本中,大括号阻止标记生成器将点视为数字文字的一部分,而不是作为一个单独的标记,写作:

In the working versions in @Joey's answer, the braces prevent the tokenizer from treating the dot as part of the number literal instead of as a separate token, as does writing:

1.0.toString()

1..toString()

因为tokenizer知道第二个点必须自己是一个令牌,而不是数字文字的一部分。

since the tokenizer knows that the second dot must be a token on its own, and not part of the number literal.

这篇关于在JavaScript中使用toString的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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