为什么JavaScript不允许您直接调用数字上的方法?

Ale*_*lan 13 javascript

在Ruby中,您可以这样做:

3.times { print "Ho! " } # => Ho! Ho! Ho!
Run Code Online (Sandbox Code Playgroud)

我尝试用JavaScript做到这一点:

Number.prototype.times = function(fn) {
    for (var i = 0; i < this; i++) {
        fn();
    }
}
Run Code Online (Sandbox Code Playgroud)

这有效:

(3).times(function() { console.log("hi"); });
Run Code Online (Sandbox Code Playgroud)

事实并非如此

3.times(function() { console.log("hi"); });
Run Code Online (Sandbox Code Playgroud)

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

Mus*_*usa 36

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

3..times(function() { console.log("hi"); });
Run Code Online (Sandbox Code Playgroud)

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

03.times(function() { console.log("hi"); });//octal
0x3.times(function() { console.log("hi"); });//hexadecimal
Run Code Online (Sandbox Code Playgroud)

也是指数级的

3e0.times(function() { console.log("hi"); });
Run Code Online (Sandbox Code Playgroud)

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

3 .times(function() { console.log("hi"); });
Run Code Online (Sandbox Code Playgroud)

虽然如wxactly评论中所述,缩小器将删除导致上述语法错误的空间.

  • 我反对做两个点,因为它很可能给读者造成混乱.Parantheses更具自我描述性. (5认同)
  • @AlexCoplan我猜是因为Ruby有整数和浮点类型,但JavaScript只有Number (3认同)
  • 最后一个利用空间的例子很有趣,但是依赖于不安全......当你通过缩小器运行该代码时,BAM会再次出现语法错误. (2认同)