在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评论中所述,缩小器将删除导致上述语法错误的空间.