我在下面有一个像这样的长常量值,是否可以在typescript中创建函数来减少长常量。
export const DepartTime =
['00.00', '00.30', '01.00', '01.30', '02.00', '02.30', '03.00', '03.30', '04.00', '04.30', '05.00', '05.30', '06.00', '06.30', '07.00', '07.30', '08.00', '08.30', '09.00', '09.30', '10.00', '10.30', '11.00', '11.30', '12.00', '12.30', '13.00',
'13.30', '14.00', '14.30', '15.00', '15.30', '16.00', '16.30', '17.00', '17.30', '18.00', '18.30', '19.00', '19.30',
'20.00', '20.30', '21.00', '21.30', '22.00', '22.30', '23.00', '23.30'
];这些值需要在角度下拉列表中进行绑定。
export class SelectOverviewExample implements OnInit {
days=[];
times =[];
ngOnInit(){
[...this.days] = weekdays;
[...this.times]=DepartTime;
}在html中。
<mat-form-field>
<mat-select placeholder="select Weekdays">
<mat-option *ngFor="let time of times" [value]="time">
{{time}}
</mat-option>
</mat-select>
</mat-form-field>或任何第三方框架都将支持
我已经试过了,结果如下:
var toInt = time => ((h,m) => h*2 + m/30)(...time.split(':').map(parseFloat)),
toTime = int => [Math.floor(int/2), int%2 ? '30' : '00'].join(':'),
range = (from, to) => Array(to-from+1).fill().map((_,i) => from + i),
eachHalfHour = (t1, t2) => range(...[t1, t2].map(toInt)).map(toTime);
console.log(eachHalfHour('00:00', '23:30'))但我需要一个数字以00:00,00:30,01.00,01.30... 09.30开头。O/p

通过使用moment js,我得到了一个解决方案,但需要为单位数添加0前缀
const locale = 'en'; // or whatever you want...
const hours = [];
moment.locale(locale); // optional - can remove if you are only dealing with one locale
for(let hour = 0; hour < 24; hour++) {
hours.push(moment({ hour }).format('H:mm'));
hours.push(
moment({
hour,
minute: 30
}).format('H:mm')
);
}
console.log(hours);

发布于 2018-09-06 23:58:48
我不认为你可以减少它。这可能没有帮助,但以下是JS版本:
var foo = [];
for (var i = 0; i <= 48; i++) {
var n = i%2==0 ? i/2+'.00' : (i+1)/2-1+'.30';
if(n<10) //zero-left padding
n = '0'+n;
foo.push(n);
}
console.log(foo);发布于 2018-09-07 13:38:05
下面的代码对我有效,我已经尝试过使用https://stackoverflow.com/a/8043061/9516784
var hrs = [];
for (var i = 0; i <= 48; i++) {
var n = i%2==0 ? i/2+'.00' : (i+1)/2-1+'.30';
if(n<10) {
n = '0'+n;
}
hrs.push(n);
}发布于 2020-10-15 20:32:42
你可以只使用除以2。
let DepartTime = [...Array(48)].map((e, i) => {
return (i/2<10 ? '0' : '') + (i/2 - i/2 % 1) + (i/2 % 1 != 0 ? '.30' : '.00');
});
console.log(DepartTime);
https://stackoverflow.com/questions/52207587
复制相似问题