Para un enfoque más natural, prueba este pequeño fragmento. Funciona con Date
objetos y así como una función regular:
'use strict';
(function(d){
var mL = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
var mS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'June', 'July', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec'];
d.prototype.getLongMonth = d.getLongMonth = function getLongMonth (inMonth) {
return gM.call(this, inMonth, mL);
}
d.prototype.getShortMonth = d.getShortMonth = function getShortMonth (inMonth) {
return gM.call(this, inMonth, mS);
}
function gM(inMonth, arr){
var m;
if(this instanceof d){
m = this.getMonth();
}
else if(typeof inMonth !== 'undefined') {
m = parseInt(inMonth,10) - 1; // Subtract 1 to start January at zero
}
return arr[m];
}
})(Date);
puede copiar y pegar directamente esto, a continuación, utilizar de esta manera:
var today = new Date();
console.log(today.getLongMonth());
console.log(Date.getLongMonth(9)); // September
console.log(today.getShortMonth());
console.log(Date.getShortMonth('09')); // Sept
Esta técnica proporcionará flexibilidad en cuanto a la forma en que el índice y cómo acceder a él. Al usar el objeto Date
funcionará correctamente, pero si lo usa como una función independiente, considera los meses en formato legible para personas del 1-12.
Fiddle with it!
Para que quede claro que está creando un objeto no una matriz. En realidad estás definiendo las propiedades del mes. Por esta razón no obtendrá lo que espera si 'alerta (month.length);' – qw3n
Lo siento, debería haber dicho, estoy creando un nuevo objeto de matriz ... –
¿Soy el único que vine aquí solo para copiar- pegar la matriz de mes de las respuestas? (porque soy demasiado perezoso para escribir solo) –