QuocVi1994 / Blog

frontend daily summary
8 stars 0 forks source link

[知识沉淀] 一些常见的判断类型的函数 utils #97

Open QuocVi1994 opened 3 years ago

QuocVi1994 commented 3 years ago

判断值是否为undefined或null

function isUndefOrNan (v) {
    return v === undefined || v === null
}

console.log(isUndefOrNan(''), isUndefOrNan(null), isUndefOrNan([]))
QuocVi1994 commented 3 years ago

判断值是否是一个对象

function isObject(v) {
  return typeof v === "object" && Array.isArray(v) && v !== null;
}
QuocVi1994 commented 3 years ago

判断一个值是否是纯的对象

const _toString = Object.prototype.toString
function isPureObject(v) {
    return _toString.call(v) === '[object Object]'
}
console.log(isPureObject(Object.create({}))); // true 
QuocVi1994 commented 3 years ago

判断值是否是一个RegExp

function isRegExp(v) {
    return _toString.call(v) === '[object RegExp]'
}

console.log(isRegExp(new RegExp()), isRegExp(Object.create(null))); // true false
QuocVi1994 commented 3 years ago

将某个值转换成 Number ,失败则返回原值


function toNumber(v) {
    const n = parseFloat(v)
    return isNaN(n) ? v : n;
}

console.log(toNumber('889'), toNumber('88x9')); // 889 88
QuocVi1994 commented 3 years ago

将任意值转成一个字符串

function toString(v) {
    return v == null
    ? ''
    : Array.isArray(v) || (isPureObject(v) && val.toString === _toString)
        ? JSON.stringify(v, null , 2)
        : String(v)
}