Passing an array to the Javascript Date constructor, is it standard?

前端 未结 4 905
轻奢々
轻奢々 2020-12-18 22:21

This works in Chrome:

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

And I get June 5, 2012. I also tried on an Androi

4条回答
  •  遥遥无期
    2020-12-18 22:44

    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.

    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().

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

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

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

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

    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.

提交回复
热议问题