我正在研究制作日历的程序。以YYYY / MM / DD格式记录数字时,应发生以下情况:
console.log(talkingCalendar("2004/11/01")); => November 1st, 2004
console.log(talkingCalendar("2007/11/11")); => November 11th, 2011
console.log(talkingCalendar("1987/08/24")); => August 24th, 1987
这是我正在研究的:
function tensFn(day) {
var output = 0;
if (day.length > 1) {
output = day[0];
}
return output;
}
function getOrdinal(day) {
var ones = day.toString().split('').pop();
ones = parseInt(ones);
var tens = parseInt(tensFn(day), 10);
var ordinate = '';
if (tens == 0 || tens == 2) {
switch (ones) {
case 1:
ordinate = 'st';
break;
case 2:
ordinate = 'nd';
break;
case 3:
ordinate = 'rd';
break;
case 4: case 5: case 6: case 7: case 8: case 9:
ordinate = 'th';
break;
}
}
if (tens == 1) {
switch (ones) {
case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 8: case 9:
ordinate = 'th';
}
}
return ordinate;
}
这是我没有完全掌握的部分:
function getOrdinal(day) {
var ones = day.toString().split('').pop();
ones = parseInt(ones);
var tens = parseInt(tensFn(day), 10);
var ordinate = '';
作者对var的处理方式是什么,为什么将其转换为字符串,先拆分然后在解析前弹出?
答案 0 :(得分:0)
从我所见,它用来分隔日子。示例编号27分为20和7。
function getOrdinal(day) { Example day = 27
var ones = day.toString().split('').pop(); convert 27 to '27', split on chars ['2','7'] and pop '7'
ones = parseInt(ones); convert to integer the result from above 7
var tens = parseInt(tensFn(day), 10); get the first number when days length is greater than 1. In this case returns 2
}
我认为一种更好的方法是:
function getOrdinal(day){ Example day = 27
var ones = day % 10 get 27 mod 10 = 7
var tens = day / 10 |0 get difference of days / ten, then floor it. Result is 2
var ordinate = '';
...
function getOrdinal(day){
var ones = day % 10
var tens = day / 10 |0
return [ones, tens]
}
console.log(getOrdinal(27))