Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
QuocVi1994 opened this issue Apr 20, 2021 · 5 comments
Open

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

QuocVi1994 opened this issue Apr 20, 2021 · 5 comments
Assignees

Comments

@QuocVi1994
Copy link
Owner

QuocVi1994 commented Apr 20, 2021

判断值是否为undefined或null

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

console.log(isUndefOrNan(''), isUndefOrNan(null), isUndefOrNan([]))
@QuocVi1994
Copy link
Owner Author

判断值是否是一个对象

function isObject(v) {
  return typeof v === "object" && Array.isArray(v) && v !== null;
}

@QuocVi1994
Copy link
Owner Author

QuocVi1994 commented Apr 20, 2021

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

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

@QuocVi1994
Copy link
Owner Author

判断值是否是一个RegExp

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

console.log(isRegExp(new RegExp()), isRegExp(Object.create(null))); // true false

@QuocVi1994
Copy link
Owner Author

QuocVi1994 commented Apr 20, 2021

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

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

console.log(toNumber('889'), toNumber('88x9')); // 889 88

@QuocVi1994
Copy link
Owner Author

QuocVi1994 commented Apr 20, 2021

将任意值转成一个字符串

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

@github-staff github-staff deleted a comment from p4u1d34n Oct 24, 2024
@github-staff github-staff deleted a comment from p4u1d34n Oct 24, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants
@QuocVi1994 and others