* 总结js的数据类型及检测

数据类型分类

基本数据类型(值类型) - 7种
  1. 数字:number
    10 10.5 -10 0 NaN非有效数组 Infinity -Infinity
  2. 字符串: string 基于单引号双引号反引号包起来的都是字符串
    '' 'aaa' '[object Object]'
  3. 布尔:boolean
    true/false
  4. 空对象指针: null
  5. 未定义: undefined
  6. symbol (es6新增,每一个symbol都是唯一值)
    let x=Symbol('A'); let y=Symbol('A'); x===y //false
    7.BigInt 表示任意大的整数
引用数据类型
  1. 对象数据类型:object
  • 普通对象: {}
    let obj={name:'a',age:'20'}
  • 数组对象: []
    let arr=[1,'a',true];
  • RegExp正则对象:/^$/
  • 日期对象:new Date
  • 数学函数对象 Math
  • ...
  1. 函数数据类型 function

声明变量类型

声明新变量时,可以使用关键词 "new" 来声明其类型:
var carname=new String;
var x= new Number;
var y= new Boolean;
var cars= new Array;
var person= new Object;
Symbol类型属于ES6中新增的基本数据类型之一,内部没有construtor构造器,不能使用new关键字创建

js数据类型检测

下面是ES6中关于Object原型中toString()方法的规定:



利用Object.prototype.toString
“Object.prototype.toString.call()”可以简写为“toString.call()”
toString方法将数据由其他的形态转换成string形态(除了null和undefined),所以我们可以利用该特性做类型检测。

console.log(Object.prototype.toString.call("hello"));//[object String]
console.log(Object.prototype.toString.call(123));//[object Number]
console.log(Object.prototype.toString.call(true));//[object Boolean]
console.log(Object.prototype.toString.call(undefined));//[object Undefined]
console.log(Object.prototype.toString.call(null));//[object Null]
console.log(Object.prototype.toString.call({name: "jerry"}));//[object Object]
console.log(Object.prototype.toString.call(function(){}));//[object Function]
console.log(Object.prototype.toString.call([]));//[object Array]
console.log(Object.prototype.toString.call(new Date));//[object Date]
console.log(Object.prototype.toString.call(/\d/));//[object RegExp]
console.log(toString.call(Math)); // [object Math]
console.log(toString.call(Symbol('A')));//[object Symbol]
function foo(){}
console.log(Object.prototype.toString.call(new foo()));//[object Object]

1.isType方法

//es5方式,返回布尔值
const isType = function(type){
    return function(obj){
        return Object.prototype.toString.call(obj) === `[object ${type}]`; //注意,object后面有空格
    }
};

//es6方式,返回布尔值
const isType1 = type => obj => Object.prototype.toString.call(obj) === `[object ${type}]`; 

// 正则匹配,返回真正的类型值
const isType2 = type =>(/^\[object\s(.*)\]$/.exec(Object.prototype.toString.call(type)))[1];

// 使用,先定义要检测的类型,传入Object.prototype.toString.call返回的值,如:Array,Number...
const isArray = isType('Array');// 注意首字母大写
const isSymbol = isType1('Symbol');
isArray([1,2,3]) ;// true
isSymbol(Symbol()); // true
isType2(null); // 'Null'

is(value, typeString)方法

// 利用Object#toString()检测类型

var _toString = Object.prototype.toString;

function is(value, typeString) {
    // 获取到类型字符串
    var stripped = _toString.call(value).replace(/^\[object\s|\]$/g, '');
    return stripped === typeString;
}

is(null, 'Null');               // true
is(undefined, 'Undefined');     // true
is(3, 'Number');                // true
is(true, 'Boolean');            // true
is('hello', 'String');          // true
is(Symbol(), 'Symbol');         // true
is({}, 'Object');               // true
is([], 'Array');                // true
is(function(){}, 'Function');   // true
is(/\w+/, 'RegExp');            // true
is(new Date, 'Date');           // true
is(new Error, 'Error');         // true
is(new Map, 'Map');             // true
is(new Set, 'Set');             // true
  1. 类型检测也可以用以下函数
  • typeof 能判断类型有:number、string、boolean、symbol、undefined、function; object、array、null 的变量都返回 object
  • Array 为 js 的原生对象,它有一个静态方法:Array.isArray(),能判断参数是否为数组
  • instanceof 运算符返回一个布尔值,表示对象是否为某个构造函数的实例(arr instanceof Array)
  • null instanceof Object //false
  • instanceof 在跨 frame 对象构建的场景下会失效
  • 支持 Array.isArray() 方法的浏览器有 IE9+、Firefox 4+、Safari 5+、Opera 10.5+和 Chrome。
function typeOf(ele) {
    var r;
    if(ele === null) r = null;
    else if(ele instanceof Array) r = 'Array';
    else if(ele === window) r = 'window';
    else if(ele instanceof Date) r = 'Date';
    else r = typeof ele;
    return r;
}

Boolean类型只有true 和 false
把其他类型转换为Boolean类型 只有五个值转换为false 其余都是true
0 NaN null undefined ""

参考:
isType方法封装和类型检测

值类型和引用类型区别

值类型
  • 占用空间固定,保存在栈中
  • 保存与复制的是值本身
  • 使用typeof检测数据的类型
  • 基本类型数据是值类型
引用类型
  • 占用空间不固定,保存在堆中
  • 保存与复制的是指向对象的一个指针
  • 使用instanceof检测数据类型
  • 使用new()方法构造出的对象是引用型
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。