在写 AngluarJS1.x 的老项目的时候,需要使用 ES6 以下的版本,很容易遇到拿不确定类型的变量去做业务逻辑判断。由于 ES5 缺乏类型校验,加上 AngluarJS 表单项返回值类型不确定(可能存在 undefined、null)。
首先了解一下业务逻辑:
- 【起始重量】和【目的重量】同时维护通过校验
- 【起始重量】和【目的重量】同时不维护通过校验
- 【起始重量】和【目的重量】中只有一个被维护不维护通过校验
- 【起始重量】需小于【目的重量】
然后看一下最初版的条件判断惊悚代码:
if (
(weightFrom === '' && weightTo !== '') ||
(weightFrom !== '' && weightTo == '') ||
(typeof weightFrom !== 'undefined' &&
typeof weightTo === 'undefined') ||
(typeof weightFrom === 'undefined' &&
typeof weightTo !== 'undefined') ||
(weightFrom !== null && weightTo === null) ||
(weightFrom == null && weightTo !== null)
) {
if (
!(
(typeof weightFrom === 'undefined' &&
weightTo === null) ||
(typeof weightTo === 'undefined' &&
weightFrom === null)
)
) {
notificationService.warning('重量维护不完全');
return;
}
} else if (
typeof weightFrom !== 'undefined' &&
typeof weightTo !== 'undefined' &&
weightFrom !== '' &&
weightTo !== ''
) {
if (Number(weightFrom) > Number(weightTo)) {
notificationService.warning('重量规则不正确');
return;
}
}
如果使用 Number()
将变量做转换,再进行类型校验,仍存在相同项
// NaN 'number'
console.log(Number(undefined), typeof Number(undefined));
// 0 'number'
console.log(Number(null), typeof Number(null));
// 0 'number'
console.log(Number(0), typeof Number(0));
// 1 'number'
console.log(Number(1), typeof Number(1));
// 0 'number'
console.log(Number(''), typeof Number(''));
// 123123 'number'
console.log(Number('123123'), typeof Number('123123'));
如果使用 String()
将变量做转换,再进行类型校验,貌似可以
// undefined string
console.log(String(undefined), typeof String(undefined));
// null string
console.log(String(null), typeof String(null));
// 0 string
console.log(String(0), typeof String(0));
// 1 string
console.log(String(1), typeof String(1));
// string
console.log(String(''), typeof String(''));
// 123123 string
console.log(String('123123'), typeof String('123123'));
console.log(String(undefined) === 'undefined'); // true
console.log(String(null) === 'null'); // true
console.log(String('') === ''); // true
使用 String()
修改一下以上代码,很简洁
var weightFromStr = String(weightFrom);
var weightToStr = String(weightTo);
if (
(weightFromStr === 'undefined' ||
weightFromStr === 'null' ||
weightFromStr === '') !==
(weightToStr === 'undefined' ||
weightToStr === 'null' ||
weightToStr === '')
) {
console.log('重量维护不完全');
} else {
if (Number(weightFromStr) >= Number(weightToStr)) {
console.log('重量维护不完全');
}
}