Javascript引用了一系列if-else语句



我有一个方法,并附加了一个事件侦听器,如下所示。

这种方法看起来很难看。还有其他重构方法吗?

任何建议或想法都将不胜感激。

document.querySelector('dateInput').addEventListener('input', func.validateCalendar, false);
const func = {
validateCalendar({target}){
const tmpArr = Array.from(target.value.replace(/[^0-9.]/g, ''));

if( tmpArr.length === 0 ){

target.value = '';

}else if( tmpArr.length === 4){

target.value = tmpArr.join('');

}else if( tmpArr.length === 5 ){ //month first digit 

const month1 = +tmpArr[4]

console.log('len:5, month1: ', month1);

if( month1 > 1 ){
tmpArr.splice(4,1, '');
}

tmpArr.splice(4,0, '-');

target.value = tmpArr.join('');

}else if( tmpArr.length === 6){ //month second digit 
const month1 = +tmpArr[4];
const month2 = +tmpArr[5];

const cond1 = month1 === 0 && month2 === 0;
const cond2 = month1 === 0 && month2 > 9;
const cond3 = month1 === 1 && month2 > 2

if( cond1 || cond2 || cond3 ){
tmpArr.splice(5,1, '');
}

tmpArr.splice(4,0, '-');

target.value = tmpArr.join('');
}else if( tmpArr.length === 7 ){ //day first digit 
const month = +tmpArr.slice(4,6).join('');
const day1 = +tmpArr[6];

console.log('len 7 : day1 ', day1);

const cond1 = month !== 2 && day1 > 3;
const cond2 = month === 2 && day1 > 2

if( cond1 || cond2 ){
tmpArr.splice(6,1, '');
}

tmpArr.splice(4,0, '-')
tmpArr.splice(7,0, '-');

target.value = tmpArr.join('');

}else if( tmpArr.length === 8 ){ //day second digit 

const year = +tmpArr.slice(1,4).join('');

const month = +tmpArr.slice(4,6).join('');

const day = +tmpArr.slice(6,8).join('');

const monthsIn31 = [1, 3, 5, 7, 8, 10, 12];
const monthsIn30 = [4, 6, 9, 11];

const cond1 = day === 0;
const cond2 = monthsIn31.includes(month) && day > 31;
const cond3 = monthsIn30.includes(month) && day > 30;
const cond4 = month === 2;

if( cond1 || cond2 || cond3){
tmpArr.splice(7,1, '');
}

if( cond4 ){
const cond1 = moment([year]).isLeapYear() && day > 29;
const cond2 = !moment([year]).isLeapYear() && day > 28
if( cond1 || cond2 ){
tmpArr.splice(7,1, '');
}
}
console.log('len 8 : ', target.value);

tmpArr.splice(4,0, '-')
tmpArr.splice(7,0, '-');

target.value = tmpArr.join('');
}else if( tmpArr.length > 8 ){
target.value = target.value.slice(0, -1);
}
},
}

如果只是一次又一次地检查变量,则可以尝试switch..case

因此,如果你目前有:

var a = 5
if(a === 5){
console.log("Five");
} else if(a === 7) {
console.log("Seven");
} else if (a === 9) {
console.log("Nine");
} 
// ... and so on
else {
console.log("Irrelevant");
}

这相当于的switch..case

var a = 5
switch(a) {
case 5:
console.log("Five");
break;

case 7:
console.log("Seven");
break;

// ... and so on
default:
console.log("Irrelevant");

}

然而,同时if..else if使用大括号{}来限制条件的范围,switch..case使用break来限制条件。如果且仅当正确放置break时,switch..case中的default等效于if..else中的else

如果您忘记放置break,它将执行所有放置在满足条件下的情况,直到找到switch..case语句的breakreturndefault或闭合花括号}

最新更新