企业网站 阿里云,所有网站名称大全,WordPress阿柳云,wordpress4.7.2写文章JavaScript的数据类型检测
typeof操作符
适用场景 基本数据类型快速判断#xff1a;适用于快速判断变量是否为number、string、boolean、undefined、function等基本数据类型。比如在函数参数检查中#xff0c;若要求传入数字参数#xff0c;可用typeof来初步判断。函数类型…JavaScript的数据类型检测
typeof操作符
适用场景 基本数据类型快速判断适用于快速判断变量是否为number、string、boolean、undefined、function等基本数据类型。比如在函数参数检查中若要求传入数字参数可用typeof来初步判断。函数类型判断能轻松判断一个变量是否为函数类型在处理回调函数等场景中很实用。 示例
console.log(typeof 123); // number
console.log(typeof abc); // string
console.log(typeof true); // boolean
console.log(typeof undefined); // undefined
console.log(typeof function(){}); // functioninstanceof操作符
适用场景 自定义对象类型判断在面向对象编程中用于判断一个对象是否是某个自定义构造函数的实例方便进行多态操作和类型特定的方法调用。内置对象类型细分可区分内置对象的具体类型如判断一个对象是否为Array、Date等。 示例
const arr [];
console.log(arr instanceof Array); // trueconst date new Date();
console.log(date instanceof Date); // trueconstructor属性
适用场景 简单类型判断与回溯可用于快速判断基本数据类型和简单对象的构造函数来源在一些需要快速追溯数据类型创建源头的场景中有用。简单对象类型识别对于通过构造函数创建的简单对象可通过constructor判断其类型。 示例
const num 42;
console.log(num.constructor Number); // truefunction Person(name) {this.name name;
}
const person new Person(John);
console.log(person.constructor Person); // trueObject.prototype.toString.call()方法
适用场景 精准类型判断在需要精确判断数据类型尤其是在区分null、array与普通object等容易混淆的类型时是首选方法。通用类型检测工具可用于编写通用的类型检测工具函数适用于各种复杂场景下的数据类型检查。 示例
console.log(Object.prototype.toString.call(123)); // [object Number]
console.log(Object.prototype.toString.call(abc)); // [object String]
console.log(Object.prototype.toString.call(null)); // [object Null]
console.log(Object.prototype.toString.call([])); // [object Array]
console.log(Object.prototype.toString.call({})); // [object Object]Array.isArray()方法
适用场景 专门用于判断一个值是否为数组在处理数组相关的操作确保操作的数据是数组类型时使用。示例
console.log(Array.isArray([])); // true
console.log(Array.isArray({})); // false基于正则表达式的类型判断
适用场景 字符串格式验证用于验证字符串是否符合特定格式如邮箱、电话号码等。数据格式规范化在数据输入、数据清洗等场景中确保数据格式的正确性和一致性。 示例
const emailRegex /^[a-zA-Z0-9._%-][a-zA-Z0-9.-]\.[a-zA-Z]{2,}$/;
console.log(emailRegex.test(testexample.com)); // true
console.log(emailRegex.test(invalid_email)); // false