变量数据类型判断

常用变量的数据类型

  1. string: 字符串类型
  2. number: 数值类型
  3. array: 数组类型
  4. object: 对象类型
  5. boolean: 布尔类型
  6. null: 空类型

说到数据类型的判断,最开始的都应该想到typeof,例如:

var a = "1", b = 2, c = [1, "2"], d = {key: 3}, e = true, f= null;
console.log('a : ', typeof a);
console.log('b : ', typeof b);
console.log('c : ', typeof c);
console.log('d : ', typeof d);
console.log('e : ', typeof e);
console.log('f : ', typeof f);
typeof效果图

我们可以看到用typeof无法判断数组、对象和空类型。


下面给大家介绍一个好的判断数据类型的方法原型对象,例如:

var a = "1", b = 2, c = [1, "2"], d = {key: 3}, e = true, f= null;
var getType = function(o){
    return Object.prototype.toString.call(o).slice(8, -1);
}
console.log('a : ', getType(a));
console.log('b : ', getType(b));
console.log('c : ', getType(c));
console.log('d : ', getType(d));
console.log('e : ', getType(e));
console.log('f : ', getType(f));
prototype原型对象效果图

90后小生,爱编程,爱运营,文艺与代码齐飞,魅力与智慧共存的全栈开发者一枚。

作者:Anting全栈开发 技术博客://www.greatytc.com/u/259b7db6cc20
来源:简书
学习交流群: 260352626 编程微刊-技术交流④
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。