Here's the shortest I can get it:
(这是我能得到的最短的:)
<script>document.write(new Date().getFullYear())</script>
That will work in all browsers I've run across.
(这将适用于我所运行的所有浏览器。)
How I got there:
(我如何到达那里:)
- You can just call
getFullYear
directly on the newly-created Date
, no need for a variable.(您可以直接在新创建的Date
上直接调用getFullYear
,而不需要变量。)
new Date().getFullYear()
may look a bit odd, but it's reliable: the new Date()
part is done first, then the .getFullYear()
.(new Date().getFullYear()
可能看起来有些奇怪,但是很可靠:首先完成new Date()
部分,然后完成.getFullYear()
。)
- You can drop the
type
, because JavaScript is the default;(您可以删除type
,因为JavaScript是默认设置。)
this is even documented as part of the HTML5 specification , which is likely in this case to be writing up what browsers already do.(这甚至被记录为HTML5规范的一部分,在这种情况下,很可能是在写出浏览器已经做过的事情。)
- You can drop the semicolon at the end for one extra saved character, because JavaScript has "automatic semicolon insertion," a feature I normally despise and rail against, but in this specific use case it should be safe enough.
(您可以在最后一个额外的保存字符删除分号,因为JavaScript有“自动插入分号,”一个功能,我常轻视和对铁路,但在这种特定情况下使用它应该是足够安全的。)
It's important to note that this only works on browsers where JavaScript is enabled.
(重要的是要注意,这仅适用于启用了JavaScript的浏览器。)
Ideally, this would be better handled as an offline batch job ( sed
script on *nix, etc.) once a year, but if you want the JavaScript solution, I think that's as short as it gets.(理想情况下,最好将其作为脱机批处理作业(* nix上的sed
脚本等)每年处理一次,但是如果您想要JavaScript解决方案,我认为它就这么短。)
(Now I've gone and tempted fate.)((现在,我走了,去吸引命运。))
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…