与日期对象的乘法 - JavaScript [英] Multiplication with date object - javascript

查看:112
本文介绍了与日期对象的乘法 - JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现这段代码 var timeStamp = 1 * new Date(); 令我吃惊的是,自1970/01/01以来,它以毫秒为单位返回值。这相当于使用 .getTime()方法!



引擎盖下发生什么?类型转换概念在这里工作,它基本上将新的Date()值转换为毫秒?

解决方案


发生什么事情?


简短版本:



由于它在数学运算中被使用,日期被转换为一个数字,当你将日期转换为数字时,你得到的数字是从 - (例如, getTime())。



长版本:


  1. 乘法运算符调用抽象操作 ToNumber 操作数。


  2. 对于像 Date s,它调用抽象操作 ToPrimitive ,首选类型为数字。


  3. 对于大多数类型的对象(包括 Date s), ToPrimitive 调用抽象操作< a href =http://www.ecma-international.org/ecma-262/5.1/#sec-8.12.8 =nofollow> [[DefaultValue]] ,将首选类型作为提示传递。


  4. [[DefaultValue]] with hint =numbercall valueOf 对象。 ( valueOf 是一个真正的方法,与上面的抽象操作不同。)


  5. 对于日期对象, valueOf 返回时间值,您从 getTime 获得的值。







旁注:没有理由使用 var timeStamp = 1 * new Date()而不是说, var timeStamp = + new Date(),具有相同的效果。或者当然,在任何现代引擎(和垫片是微不足道的), var timeStamp = Date.now() more on Date.now )。 p>

I came across this piece of code var timeStamp = 1 * new Date(); and to my surprise it returned value in milliseconds since 1970/01/01. This is equivalent to using .getTime() method!

What's happening under the hood? Does Type Conversion concept work here, which basically converts new Date() value into the milliseconds?

解决方案

What's happening under the hood?

The short version:

Because it's being used in a math operation, the date is converted to a number, and when you convert dates to numbers, the number you get is the milliseconds-since-the-Epoch (e.g., getTime()).

The long version:

  1. The multiplication operator calls the abstract operation ToNumber on its operands.

  2. For objects like Dates, that calls the abstract operation ToPrimitive on the object, with the "preferred type" being "number".

  3. For most types of objects (including Dates), ToPrimitive calls the abstract operation [[DefaultValue]], passing along the preferred type as the "hint".

  4. [[DefaultValue]] with hint = "number" calls valueOf on the object. (valueOf is a real method, unlike the abstract operations above.)

  5. For Date objects, valueOf returns the "time value," the value you get from getTime.


Side note: There's no reason I can think of to use var timeStamp = 1 * new Date() rather than, say, var timeStamp = +new Date(), which has the same effect. Or of course, on any modern engine (and the shim is trivial), var timeStamp = Date.now() (more on Date.now).

这篇关于与日期对象的乘法 - JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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