javascript技巧

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript技巧 > JavaScript类型判断方法

JavaScript类型判断的多种方法

作者:BillKu

本文介绍了JavaScript中多种类型判断方法,包括基础类型判断、数组判断、null判断、复杂类型判断、构造函数实例判断、NaN判断、类型安全比较等,并提供了一些实用建议,帮助开发者编写更健壮的JavaScript代码,需要的朋友可以参考下

在JavaScript中,类型判断有多种方法,各有优缺点。以下是全面的类型判断指南:

1.typeof 操作符

最基本的类型判断,适用于原始类型:

typeof "hello"      // "string"
typeof 42           // "number"
typeof true         // "boolean"
typeof undefined    // "undefined"
typeof Symbol()     // "symbol"
typeof 123n         // "bigint"
typeof function(){} // "function"

// 局限性:
typeof null         // "object" (历史遗留问题)
typeof []           // "object"
typeof {}           // "object"
typeof new Date()   // "object"

2.instanceof 操作符

检查对象是否是特定构造函数的实例:

[] instanceof Array           // true
new Date() instanceof Date    // true
[] instanceof Object          // true (原型链上)

// 局限性:
"hello" instanceof String     // false
123 instanceof Number         // false

3.Object.prototype.toString.call()

最可靠的类型判断方法:

Object.prototype.toString.call("hello")     // "[object String]"
Object.prototype.toString.call(42)          // "[object Number]"
Object.prototype.toString.call(123n)        // "[object BigInt]"
Object.prototype.toString.call(true)        // "[object Boolean]"
Object.prototype.toString.call(null)        // "[object Null]"
Object.prototype.toString.call(undefined)   // "[object Undefined]"
Object.prototype.toString.call([])          // "[object Array]"
Object.prototype.toString.call({})          // "[object Object]"
Object.prototype.toString.call(new Date())  // "[object Date]"
Object.prototype.toString.call(/regex/)     // "[object RegExp]"
Object.prototype.toString.call(function(){})// "[object Function]"
Object.prototype.toString.call(Symbol())    // "[object Symbol]"

4.专用判断方法

数组判断

Array.isArray([])           // true (ES5+,最可靠)
[] instanceof Array         // true
Object.prototype.toString.call([]) === '[object Array]'  // true

// 旧浏览器兼容方法
function isArray(obj) {
    return Object.prototype.toString.call(obj) === '[object Array]';
}

NaN 判断

isNaN(NaN)                  // true (有问题:会尝试转换类型)
isNaN("hello")              // true

Number.isNaN(NaN)           // true (ES6,推荐)
Number.isNaN("hello")       // false

// 替代方案:
function isNaN(value) {
    return value !== value;  // NaN是唯一不等于自身的值
}

空值判断

// 严格相等判断
value === null      // 判断null
value === undefined // 判断undefined

// 双等号判断(可能产生意外转换)
value == null       // true if value is null or undefined

// 安全检查
if (value != null) {
    // value既不是null也不是undefined
}

5.实用类型判断函数

// 获取准确类型
function getType(value) {
    return Object.prototype.toString.call(value)
        .replace(/^\[object (\w+)\]$/, '$1')
        .toLowerCase();
}

// 类型判断工具函数
const TypeChecker = {
    isString: val => typeof val === 'string',
    isNumber: val => typeof val === 'number' && !isNaN(val),
    isBoolean: val => typeof val === 'boolean',
    isUndefined: val => val === undefined,
    isNull: val => val === null,
    isObject: val => 
        val !== null && typeof val === 'object' && !Array.isArray(val),
    isArray: val => Array.isArray(val),
    isFunction: val => typeof val === 'function',
    isDate: val => val instanceof Date,
    isRegExp: val => val instanceof RegExp,
    isError: val => val instanceof Error,
    isSymbol: val => typeof val === 'symbol',
    isBigInt: val => typeof val === 'bigint',
    isPromise: val => 
        Boolean(val && typeof val.then === 'function'),
    
    // 判断原始类型
    isPrimitive: val => 
        val === null || 
        typeof val === 'string' ||
        typeof val === 'number' ||
        typeof val === 'boolean' ||
        typeof val === 'undefined' ||
        typeof val === 'symbol' ||
        typeof val === 'bigint',
    
    // 判断类数组对象(有length属性)
    isArrayLike: val => 
        val != null && 
        typeof val !== 'function' && 
        typeof val.length === 'number'
};

// 使用示例
TypeChecker.isArray([1, 2, 3])          // true
TypeChecker.isObject({ a: 1 })          // true
TypeChecker.isPrimitive(42)             // true

6.ES6+ 新增方法

// Number类型判断
Number.isInteger(42)        // true
Number.isInteger(42.0)      // true
Number.isInteger(42.5)      // false
Number.isSafeInteger(42)    // true

// 数组类型判断
Array.isArray([])           // true

// Symbol类型
typeof Symbol() === 'symbol'

// BigInt类型
typeof 123n === 'bigint'

7.特殊情况的处理

// 判断是否为纯对象(排除数组、函数等)
function isPlainObject(obj) {
    return Object.prototype.toString.call(obj) === '[object Object]' &&
           Object.getPrototypeOf(obj) === Object.prototype;
}

// 判断是否为DOM元素
function isElement(obj) {
    return !!(obj && obj.nodeType === 1);
}

// 判断是否为空对象
function isEmptyObject(obj) {
    return isPlainObject(obj) && Object.keys(obj).length === 0;
}

// 判断是否为数值(包括字符串数字)
function isNumeric(value) {
    return !isNaN(parseFloat(value)) && isFinite(value);
}

8.最佳实践建议

  1. 基础类型判断:使用 typeof
  2. 数组判断:使用 Array.isArray()
  3. null判断:使用 value === null
  4. 复杂类型判断:使用 Object.prototype.toString.call()
  5. 构造函数实例判断:使用 instanceof
  6. NaN判断:使用 Number.isNaN()
  7. 类型安全比较:优先使用 === 而不是 ==

9.TypeScript中的类型判断

// 类型守卫
function isString(value: any): value is string {
    return typeof value === 'string';
}

// 使用示例
function process(value: string | number) {
    if (isString(value)) {
        // TypeScript知道这里是string类型
        console.log(value.toUpperCase());
    }
}

选择哪种方法取决于具体需求,但掌握这些技术可以帮助你编写更健壮的JavaScript代码。

以上就是JavaScript类型判断的多种方法的详细内容,更多关于JavaScript类型判断方法的资料请关注脚本之家其它相关文章!

您可能感兴趣的文章:
阅读全文