- List item
当js 遇上她的另一半…
说笑啦,看例子吧!!!
①:问:使用js 语法糖 判断参数是各种空类型 —>连例子都列好啦
下面是使用JS语法糖判断各种空类型的代码示例:
function checkEmpty(value) {
if (value == null || value == undefined || value === '' || Number.isNaN(value)) {
return true;
} else {
return false;
}
}
console.log(checkEmpty(null)); // true
console.log(checkEmpty(undefined)); // true
console.log(checkEmpty('')); // true
console.log(checkEmpty(0/0)); // true
console.log(checkEmpty(0)); // false
console.log(checkEmpty(false)); // false
console.log(checkEmpty('hello')); // false
console.log(checkEmpty([])); // false
上述代码使用了JavaScript中的逻辑或运算符(||
)和严格相等运算符(===
)来判断参数是否为空类型,其中:
- 如果参数为
null
或undefined
,则视为空类型; - 如果参数为一个空字符串(
''
),则视为空类型; - 如果参数为
NaN
,则视为空类型; - 其他情况均视为非空类型。
如果你希望额外考虑其他情况,比如空数组或空对象等,可以在函数中加入额外的判断条件。
② 问:使用js实现一个函数,有两个参数,第一个是日期,第二个是输出格式,返回该格式日期
我们可以先创建一个Date对象,获取传入日期的年、月、日、小时、分钟和秒数,然后根据输出格式,对这些数据进行格式化处理,并拼接成一个字符串返回。
以下是一个简单的实现:
function formatDate(date, format) {
const year = date.getFullYear();
const month = date.getMonth() + 1;
const day = date.getDate();
const hour = date.getHours();
const minute = date.getMinutes();
const second = date.getSeconds();
const o = {
'M+': month,
'd+': day,
'h+': hour % 12 === 0 ? 12 : hour % 12,
'H+': hour,
'm+': minute,
's+': second,
'q+': Math.floor((month - 1) / 3) + 1,
'S': date.getMilliseconds()
};
// 替换年份
if(/(y+)/.test(format)) {
format = format.replace(RegExp.$1, (year + '').substr(4 - RegExp.$1.length));
}
// 替换其他部分
for(let k in o) {
if(new RegExp(`(${k})`).test(format)) {
format = format.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)));
}
}
// 替换AM/PM
if(/(a+)/i.test(format)) {
format = format.replace(RegExp.$1, hour < 12 ? 'am' : 'pm');
}
return format;
}
在这个实现中,我们首先定义了一些常见的格式占位符,然后通过正则表达式匹配格式字符串,将相应的数值替换进去。其中,最复杂的是替换年份的部分,这里使用了字符串的substr方法实现了不同位数的年份替换。同时,为了支持AM/PM的输出,在格式字符串中也加入了一个a+的占位符。最后,我们返回格式化后的字符串即可。
好啦😀,玩到这里了,快去试试吧,宝~