JS——数据类型及判断

前置知识

基本类型: 存放在栈内存中的简单数据段,数据大小确定,内存空间大小可以分配。
5种基本数据类型有Undefined、Null、Boolean、Number 和 String,它们是直接按值存放的,所以可以直接访问。
引用类型: 存放在堆内存中的对象,变量实际保存的是一个指针,这个指针指向另一个位置。每个空间大小不一样,要根据情况开进行特定的分配。
当我们需要访问引用类型(如对象,数组,函数等)的值时,首先从栈中获得该对象的地址指针,然后再从堆内存中取得所需的数据。

原始的数据类型(五种)

String(字符串)、Number(数字)、Boolean(布尔值)、Null(空)、Undefined(未定义)

引用数据类型

Object、Array、Function

判断数据类型

typeof

返回值有6种,都是字符串形式
String、Number、Boolean、Undefined、Object、Function

console.log(typeof(123))    // Number
console.log(typeof('abc'))  // String
console.log(typeof(true))   // Boolean
console.log(typeof(undefined)) // Undefined
console.log(typeof(null))   // Object,历史遗留问题,null类型被当做一个空对象引用
console.log(typeof({ }))    // Object
console.log(typeof([ ]))    // Object
console.log(typeof(console.log()))  // Undefined
function sum() {}
console.log(typeof(sum))    // Function
console.log(typeof([1, 2])) // Object

typeof的缺陷:
无法正确判断数组,判断结果为Object。
无法判断null类型,判断结果为Object。

instanceof

用来判断某个构造函数的 prototype 属性所指向的对象是否存在于另外一个要检测对象的原型链上

console.log(({}) instanceof Object)              // true
console.log((null) instanceof Object)            // false
console.log(([]) instanceof Array)               // true
console.log((/aa/g) instanceof RegExp)           // true
console.log((function(){}) instanceof Function)  // true
Object.prototype.toString.call(需要检查的对象)
console.log(Object.prototype.toString.call(null)) // [object Null]
console.log(Object.prototype.toString.call({ })) // [object Object]
console.log(Object.prototype.toString.call([ ])) // [object Array]
console.log(Object.prototype.toString.call(sayIntroduce)) // [object Function]
console.log(Object.prototype.toString.call(undefined)) // [object Undefined]
console.log(Object.prototype.toString.call('abc'))// [object String]
console.log(Object.prototype.toString.call(123)) // [object Number]
console.log(Object.prototype.toString.call(true)) // [object Boolean]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值