我需要生成一个对象数组,该对象数组包含三个键,其字符串值从1到31。字符串应包含两个字符,这意味着1-9前面应该为0。
const days = [
{ key: '01', value: '01', text: '01' },
{ key: '02', value: '02', text: '02' },
{ key: '03', value: '03', text: '03' },
...
{ key: '30', value: '30', text: '30' },
{ key: '31', value: '31', text: '31' }
]
我认为应该做的更短,更聪明,然后是我想到的解决方案:
const days = Array.from({ length: 31 }, (v, k) => {
return {
key: k > 10 ? (k + 1).toString() : '0' + (k + 1),
value: k > 10 ? (k + 1).toString() : '0' + (k + 1),
text: k > 10 ? (k + 1).toString() : '0' + (k + 1)
}
})
如果我不从值1开始怎么办?例如,从1950年到现在的年份中相同的数组(以相反的顺序):
const years = [
{ key: '2018', value: '2018', text: '2018' },
...
{ key: '1950', value: '1950', text: '1950' }
]
答案 0 :(得分:2)
您可以简单地使用padStart()
const days = Array.from({length: 31}, (v, k) => {
let o = (k + 1).toString().padStart(2, '0');
return {key: o,value: o,text: o}
});
console.log(days);
关于年份,结构相同,但不添加1,而是添加开始年份。
const years = Array.from({length: 20}, (v, k) => {
let o = (k + 2000);
return {key: o,value: o,text: o}
});
console.log(years);
文档:db.read_text
答案 1 :(得分:0)
我认为应该做得更短,更聪明...
好吧,您当然可以少重复一遍:
const days = Array.from({ length: 31 }, (v, k) => {
const value = k > 10 ? (k + 1).toString() : '0' + (k + 1);
return {
key: value,
value,
text: value
};
});
实时示例:
const days = Array.from({ length: 31 }, (v, k) => {
const value = k > 10 ? (k + 1).toString() : '0' + (k + 1);
return {
key: value,
value,
text: value
};
});
console.log(days);
.as-console-wrapper {
max-height: 100% !important;
}
如果我不从值1开始怎么办?
只需添加所需的值:
const startYear = 2018;
const years = Array.from({ length: 5 }, (v, k) => {
const value = String(k + startYear);
return {
key: value,
value,
text: value
};
});
实时示例:
const startYear = 2018;
const years = Array.from({ length: 5 }, (v, k) => {
const value = String(k + startYear);
return {
key: value,
value,
text: value
};
});
console.log(years);
.as-console-wrapper {
max-height: 100% !important;
}
自然地,如果您需要可重用的内容,请将其包装在函数中。
答案 2 :(得分:0)
const days = Array.from({ length: 31 }, (v, i) =>
({ key: v = (++i > 9 ? '' : '0') + i, value: v, text: v }) );
const years = Array.from({ length: 2018 - 1950 + 1 }, (v, i) =>
({ key: v = 2018 - i + '', value: v, text: v }) );
console.log( JSON.stringify( days ).replace(/},/g, '},\n ') );
console.log( JSON.stringify( years ).replace(/},/g, '},\n ') );