为什么JavaScript不允许您直接调用数字上的方法? [英] Why doesn't JavaScript let you call methods on numbers directly?

查看:80
本文介绍了为什么JavaScript不允许您直接调用数字上的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Ruby中,你可以这样做:

In Ruby, you can do this:

3.times { print "Ho! " } # => Ho! Ho! Ho!

我尝试在JavaScript中执行此操作:

I tried to do it in JavaScript:

Number.prototype.times = function(fn) {
    for (var i = 0; i < this; i++) {
        fn();
    }
}

这有效:

(3).times(function() { console.log("hi"); });

这不是

3.times(function() { console.log("hi"); });

Chrome给我一个语法错误:意外的令牌ILLEGAL。为什么?

Chrome gives me a syntax error: "Unexpected token ILLEGAL". Why?

推荐答案

数字后的代表小数点数字,你将不得不使用另一个来访问一个属性或方法。

The . after the digits represents the decimal point of the number, you'll have to use another one to access a property or method.

3..times(function() { console.log("hi"); });

这仅适用于十进制文字。对于八进制和十六进制文字,您只使用一个

This is only necessary for decimal literals. For octal and hexadecimal literals you'd use only one ..

03.times(function() { console.log("hi"); });//octal
0x3.times(function() { console.log("hi"); });//hexadecimal

也是指数

3e0.times(function() { console.log("hi"); });

您也可以使用空格,因为数字中的空格无效,因此没有歧义。

You can also use a space since a space in a number is invalid and then there is no ambiguity.

3 .times(function() { console.log("hi"); });

虽然在评论中由 wxactly 所述缩小器会删除导致上述语法错误的空格。

Although as stated by wxactly in the comments a minifier would remove the space causing the above syntax error.

这篇关于为什么JavaScript不允许您直接调用数字上的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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