Osc*_*son 17 javascript arrays date object
我怎样才能让它变得更好?
var month = new Array();
month['01']='Jan';
month['02']='Feb';
month['03']='Mar';
Run Code Online (Sandbox Code Playgroud)
好像这样做很好:
var months = new Array(['01','Jan'],['02','Feb'],['03','Mar']);
Run Code Online (Sandbox Code Playgroud)
例如.无论如何要简化它?
Jim*_*uck 31
对于更自然的方法,请尝试这个小片段.它适用于Date
对象,也可以作为常规函数:
'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);
Run Code Online (Sandbox Code Playgroud)
你可以直接复制并粘贴它,然后像这样使用它:
var today = new Date();
console.log(today.getLongMonth());
console.log(Date.getLongMonth(9)); // September
console.log(today.getShortMonth());
console.log(Date.getShortMonth('09')); // Sept
Run Code Online (Sandbox Code Playgroud)
此技术将为您索引的方式以及访问方式提供灵活性.使用该Date
对象时,它将正常工作,但如果将其用作独立功能,则会以1-12的人类可读格式考虑月份.
Gab*_*oli 22
这应该做..
var months = {'01':'Jan', '02':'Feb'};
alert( months['01'] );
Run Code Online (Sandbox Code Playgroud)
这是一个动态解决方案,不需要对几个月的数据进行硬编码:
const month = f=>Array.from(Array(12),(e,i)=>new Date(25e8*++i).toLocaleString('en-US',{month:f}));
Run Code Online (Sandbox Code Playgroud)
测试用例:
// Using Number Index:
month`long`[0]; // January
month`long`[1]; // February
month`long`[2]; // March
month`short`[0]; // Jan
month`short`[1]; // Feb
month`short`[2]; // Mar
month`narrow`[0]; // J
month`narrow`[1]; // F
month`narrow`[2]; // M
month`numeric`[0]; // 1
month`numeric`[1]; // 2
month`numeric`[2]; // 3
month`2-digit`[0]; // 01
month`2-digit`[1]; // 02
month`2-digit`[2]; // 03
// Using String Index:
let index_string = '01';
month`long`[index_string-1]; // January
month`short`[index_string-1]; // Jan
month`narrow`[index_string-1]; // J
month`numeric`[index_string-1]; // 1
month`2-digit`[index_string-1]; // 01
Run Code Online (Sandbox Code Playgroud)
为什么不:
var month = [
'Jan',
'Feb',
// ...
'Dec'];
Run Code Online (Sandbox Code Playgroud)
要从数字中获取月份名称,您需要执行以下操作:
var monthNum = 2; // February
var monthShortName = month[monthNum-1];
Run Code Online (Sandbox Code Playgroud)