在JS中调用数字文字的函数有哪些规则? [英] What are the rules for invoking functions on number literals in JS?

查看:71
本文介绍了在JS中调用数字文字的函数有哪些规则?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

自从我开始使用JS以来,我认为在数字文字上调用函数的唯一方法是通过用parens包装它来将其置于表达式位置,如下所示:

Since I started working with JS, I've thought the only way to invoke a function on a number literal is to put it in expression position by wrapping it with parens, like so:

1.toString();
// SyntaxError: identifier starts immediately after numeric literal

(1).toString();
// "1"

今天,我想到尝试这个:

Today, it occurred to me to try this:

0.1.toString();
// "0.1"

为什么这样做?指向官方规范的指针会很棒。

Why does this work? A pointer into the official spec would be great.

编辑歧义是我的第一个想法,但随后决定<$ c中没有歧义$ c> 1.toString()。这比我初想的要深,但我仍然认为我是对的。原因如下:

Edit Ambiguity was my first thought, but then decided that there's no ambiguity in 1.toString() either. It's deeper than I first thought, but I still think I'm right. Here's why:

物业名称​​可以以数字开头

Property names can begin with digits

var obj = { "1" : 1, "2" : 2 };

以数字开头的属性名称只能用方括号引用

obj.1;
// SyntaxError: Unexpected token ILLEGAL
obj['1'];
// 1

此外:

1['toString']();
// '1'

因此, 1。后跟任何非数字将始终是方法调用或属性访问,绝不是十进制数。同样, 1。后跟任何数字将始终是十进制数字,绝不是方法调用或属性访问。

Therefore, 1. followed by any non-digit will always be a method call or property access, never a decimal number. Likewise, 1. followed by any digit will always be a decimal number, never a method call or property access.

推荐答案

一旦在 0.1 中看到第一个,那么后续 不能成为该号码的一部分。

Once it's seen the first . in 0.1, then a subsequent . cannot be part of the number.

这完全是歧义。

编辑—规范第7.8.3节明确坚持这一点:

edit — section 7.8.3 of the spec explicitly insists on this:


紧跟NumericLiteral之后的源字符不能是 IdentifierStart DecimalDigit

我不确定那是什么阻止,但是JavaScript词法分析器非常粗糙,主要得益于正则表达式的文字语法以及需要一个奇怪的解析器 - 词法分析器来处理它。

I'm not sure exactly what that's trying to prevent, but the JavaScript lexer is pretty gnarly, mostly thanks to the regex literal grammar and the need for a weird parser-lexer hack to deal with that.

这篇关于在JS中调用数字文字的函数有哪些规则?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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