将数组传递给Javascript Date构造函数,是标准的吗? [英] Passing an array to the Javascript Date constructor, is it standard?

查看:116
本文介绍了将数组传递给Javascript Date构造函数,是标准的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可以在Chrome中使用:

This works in Chrome:

var dateArray = [2012, 6, 5];
var dateObject = new Date(dateArray);

而且我到2012年6月5日。我也尝试过一个Android浏览器,我得到相同的结果。但是,在Firefox或Safari中也不行。我可以说:

And I get June 5, 2012. I also tried on an Android browser and I get the same results. However, the same does not work in Firefox or Safari. I could say:

var dateObject = new Date(2012, 6, 5);

但是那将是2012年7月5日,因为它应该是,也是我得到与Chrome 。

But that would be July 5, 2012, as it should, and is also what I get with Chrome.

我的问题是ECMA标准的第一个例子: Chrome只是越来越流行,我可以期待其他浏览器在未来能够支持吗?还是只是一些v8-ism,我应该避免可移植性?

My question: is the first example part of the ECMA standard? Is it just that Chrome is more bleeding edge and could I expect other browsers to support it in the future? Or is it just some v8-ism that I should avoid for portability?

我一直在试图找到这个特定形式的Date构造函数的引用,但无法获取任何。

I've been trying to find references for this specific form of the Date constructor but could not get any.

推荐答案

ES5规范详细说明了 日期构造函数的新日期(值)表格 。在处理此表单的算法中,通过调用值转换为原始值.2rel =noreferrer> [[DefaultValue]] 对象的内部方法

The ES5 spec details the new Date(value) form of the Date constructor. In the algorithm for handling this form, value is converted to a primitive value by calling the [[DefaultValue]] internal method of the object.

将数组转换为原始值基本上是通过将数组转换为字符串来完成的。将数组转换为字符串( Array.prototype.toString )与调用 dateArray.join()相同。

Converting an array to a primitive value is basically done by converting the array to a string. Converting an array to a string (Array.prototype.toString) is effectively the same as calling dateArray.join().

因此,您对 Date 构造函数的调用将有效地如下所示:

Therefore, your call to the Date constructor will effectively look like this:

var dateObject = new Date("2012,6,5");

如果字符串可以被 Date.parse 方法,你最终会得到一个 Date 实例

If the string can be recognised by the Date.parse method, you will end up with a Date instance.

这种形式的 Date 构造函数也是新建日期(dateString)中的 MDN上列出 )。

This form of the Date constructor is also listed on MDN as new Date(dateString).

当您传递数组时,Firefox似乎失败,但如果传递该数组的字符串表示,则会成功。我会说这可能是Firefox的错误,但是我可能会误解ES5规范。

Firefox seems to fail when you pass an array, but it succeeds if you pass the string representation of that array. I would say that that's probably a Firefox bug, but I may be misinterpreting the ES5 spec.

这篇关于将数组传递给Javascript Date构造函数,是标准的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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