首页 > 其他分享 >js:typeof和Object.prototype.toString检测数据类型

js:typeof和Object.prototype.toString检测数据类型

时间:2023-06-11 23:01:15浏览次数:49  
标签:object console log Object 数据类型 js toBe expect getType

(目录)

typeof 检测数据类型

console.log(typeof 100); //"number"
console.log(typeof "abc"); //"string"
console.log(typeof false); //"boolean"
console.log(typeof undefined); //"undefined"
console.log(typeof function () {}); //"function"

console.log(typeof null); //"object"
console.log(typeof [1, 2, 3]); //"object"
console.log(typeof { a: 1, b: 2, c: 3 }); //"object"

console.log(typeof new Date()); //"object"
console.log(typeof /^[a-zA-Z]{5,20}$/); //"object"
console.log(typeof new RegExp('\d+')); //"object"
console.log(typeof new Error()); //"object"
console.log(typeof new Number(100)); //'object'

console.log(typeof new String("abc")); // object
console.log(typeof new Boolean(true)); // object

toString 检测数据类型

var toString = Object.prototype.toString

console.log(toString.call(123)); //"[object Number]"
console.log(toString.call(new Number(100))); // [object Number]

console.log(toString.call('abc')); //"[object String]"
console.log(toString.call(new String("abc"))); // [object String]

console.log(toString.call(true)); //"[object Boolean]"
console.log(toString.call(new Boolean(true))); // [object Boolean]

console.log(toString.call(undefined)); //"[object Undefined]"
console.log(toString.call(null)); //"[object Null]"
console.log(toString.call(function(){ })); //"[object Function]"

console.log(toString.call([1, 2, 3, 4])); //"[object Array]"
console.log(toString.call({name:'wenzi', age:25})); //"[object Object]"

console.log(toString.call(new Date())); //"[object Date]"
console.log(toString.call(/^[a-zA-Z]{5,20}$/)); //"[object RegExp]"
console.log(toString.call(new RegExp('\d+'))); // [object RegExp]
console.log(toString.call(new Error())); //"[object Error]"

工具方法

type-util.ts

/**
 * 类型枚举值
 */
export const typeEnum = {
  NUMBER: "number",
  STRING: "string",
  BOOLEAN: "boolean",
  ARRAY: "array",
  OBJECT: "object",
  FUNCTION: "function",
  UNDEFINED: "undefined",
  NULL: "null",
  DATE: "date",
  REGEXP: "regexp",
  ERROR: "error",
};

/**
 * 获取对象的数据类型
 * @param obj 
 * @returns string
 */
export function getType(obj: any): string {
  // 如果不是object类型的数据,直接用typeof就能判断出来

  const objType = typeof obj;

  if (objType !== typeEnum.OBJECT) {
    return objType;
  }

  // 如果是object类型数据,准确判断类型必须使用Object.prototype.toString.call(obj)的方式才能判断
  return Object.prototype.toString
    .call(obj)
    .replace(/^\[object (\S+)\]$/, "$1")
    .toLowerCase();
}

/**
 * 判断是否为对象
 * @param value 
 * @returns boolean
 */
export function isObject(value: any): boolean {
  return getType(value) == typeEnum.OBJECT;
}

/**
 * 判断是否是数组
 * @param value 
 * @returns boolean
 */
export function isArray(value: any): boolean {
  return Array.isArray(value);
}

/**
 * 判断对象是否为空
 * null {} [] "" 0 false
 * @param {any} value
 */
export function isEmpty(value: any): boolean {
  if (!value) {
    // false null "" 0
    return true;
  } else if (isObject(value)) {
    // 空对象 {}
    return JSON.stringify(value) == "{}";
  } else if (isArray(value)) {
    // 空数组 []
    return value.length == 0;
  } else {
    // 非空值
    return false;
  }
}

工具类测试用例

type-util.test.js

const { getType, isObject, isArray, isEmpty } = require("../src/type-util");

// test getType
test("getType", function () {
  expect(getType(123)).toBe("number");
  expect(getType(new Number(100))).toBe("number");

  expect(getType("abc")).toBe("string");
  expect(getType(new String("abc"))).toBe("string");

  expect(getType(true)).toBe("boolean");
  expect(getType(false)).toBe("boolean");
  expect(getType(new Boolean(true))).toBe("boolean");

  expect(getType(undefined)).toBe("undefined");
  expect(getType(null)).toBe("null");
  expect(getType(function () {})).toBe("function");

  expect(getType({})).toBe("object");
  expect(getType({ name: "tom", age: 25 })).toBe("object");

  expect(getType([])).toBe("array");
  expect(getType([1, 2, 3, 4])).toBe("array");

  expect(getType(new Date())).toBe("date");

  expect(getType(/^[a-zA-Z]{5,20}$/)).toBe("regexp");
  expect(getType(new RegExp("d+"))).toBe("regexp");

  expect(getType(new Error())).toBe("error");
});

// test isObject
test("isObject", function () {
  expect(isObject(null)).toBe(false);
  expect(isObject({})).toBe(true);
});

// test isArray
test("isArray", function () {
  expect(isArray(null)).toBe(false);
  expect(isArray({})).toBe(false);
  expect(isArray([])).toBe(true);
});

// test isEmpty
test("isEmpty", function () {
  expect(isEmpty(null)).toBe(true);
  expect(isEmpty(undefined)).toBe(true);
  expect(isEmpty(false)).toBe(true);
  expect(isEmpty({})).toBe(true);
  expect(isEmpty([])).toBe(true);
  expect(isEmpty(0)).toBe(true);
  expect(isEmpty('')).toBe(true);

  expect(isEmpty([1])).toBe(false);
  expect(isEmpty({ name: "tom" })).toBe(false);
  expect(isEmpty('hello')).toBe(false);
  expect(isEmpty(true)).toBe(false);
  expect(isEmpty(100)).toBe(false);
});

参考文章

标签:object,console,log,Object,数据类型,js,toBe,expect,getType
From: https://blog.51cto.com/mouday/6459276

相关文章

  • Java常用的几种JSON解析工具
    一、Gson:Google开源的JSON解析库1.添加依赖<!--gson--><dependency><groupId>com.google.code.gson</groupId><artifactId>gson</artifactId></dependency><!--lombok--><dependency><groupId>org.proje......
  • Win7使用最新的node.js(版本18.16.0)
    截至本文的发布时间2023.06.11,前端开发基础工具node.js的最新版本是18.16.0LTS可能有人要问,为什么要研究node.js在Win7系统下的兼容情况呢?你直接用Win10不就行了?如果你可以直接使用Win10,显然你不是这篇文章的推荐阅读对象,因为某些开发环境比较特殊,只能使用Win7而不允许使用Win......
  • [GPT] 监测输入框被 js 设置了值 ?input 输入框被设置了 value 值,但是没有触发 change
    1.input输入框被设置了value值,但是没有触发change事件?如果输入框的value值是通过JavaScript代码直接设置的,那么不会触发change事件,这是正常的行为。change事件只会在用户手动更改输入框的值并使其失去焦点时触发。如果输入框的value值是通过用户交互(如键盘输入......
  • [GPT] js 外部参数怎么传给 setTimeout 的匿名函数 ?
     你可以将外部参数作为setTimeout()函数的第三个参数传递,然后在匿名函数中使用这个参数。例如:varmyParam="Hello,world!";setTimeout(function(param){console.log(param);//输出:"Hello,world!"},1000,myParam); 在这个例子中,我们将外部参数myParam作......
  • Windows驱动开发学习记录-ObjectType Hook之ObjectType结构相关分析
    1、目的  在一般情况下,对于系统的常规操作如创建进程、创建互斥体、创建文件等可以进行SSDTHook进行拦截,但在x64位系统下,有PG的保护,常规的SSDTHook会导致蓝屏。但基于ObjectType的一些Hook也可以做到相应的功能且不会导致系统BSOD。 2、相关结构分析2.1XP上的相关结构......
  • JS中Map的遍历(转)
    转自:JS中Map的遍历1、forEach遍历constmap=newMap([['key1','v1'],['key2','v2'],['key3','v3']]);console.log(map);map.forEach((val,key)=>{console.log(val,key);//先输出value,再输出key})/**v1key......
  • Redis数据类型之String
    1.string类型数据的基本操作添加/修改数据:setkeyvalue获取数据:getkey删除数据:delkey添加/修改多个数据:msetkeyvaluekey1value1获取多个数据:mgetkeykey1追加信息到原始数据后边(不存在时则添加):appendkeyvalue2.string类型增减操作设置数据增加指定范围的值:incrke......
  • Vue3.js第一部分【核心篇】
    Vue3Vue核心Vue3快速上手​1.Vue3简介2020年9月18日,Vue.js发布3.0版本,代号:OnePiece(海贼王)耗时2年多、​2600+次提交、30+个RFC、600+次PR、99位贡献者github上的tags地址:​https://github.com/vuejs/vue-next/releases/tag/v3.0.0国内官网地址:​Vue.js-渐进式JavaScr......
  • jstat
    joeyon@linux$jstat-gcutil152161000100S0S1EOPYGCYGCTFGCFGCTGCT40.770.0035.880.8016.3140.08610.0250.11140.770.0035.880.8016.3140.0861......
  • Laravel 框架使用外部的js、css等文件
    Laravel框架使用外部的js、css等文件阅读有道云笔记https://note.youdao.com/s/d1ZQ9AC8Laravel项目的web虚拟主机指定的目录(即网址的根目录),项目的入口文件笔系统的静态资源目录(css、img、js、uploads)后期使用的外部静态文件都需要放到Public目录下,图中所示,可以想像成views......