toString.call()如何判断各种数据类型的类型?

2026-04-01 14:520阅读0评论SEO资源
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计603个文字,预计阅读时间需要3分钟。

toString.call()如何判断各种数据类型的类型?

判断数据类型的方法有很多。我们常用的有`typeof`,但这个方法有一定的局限性。例如:

- `typeof null` 返回 `object`- `typeof []` 返回 `object`- `typeof {}` 返回 `object`- `typeof function()`{} 返回 `function`- `typeof 2` 返回 `number`

这些例子展示了`typeof`的一些局限性。

大家都知道判断数据类型的方法有很多。我们常用的有typeof但是,这个方法有一定的局限性。

typeof null // "object" typeof [8] // "object" typeof {} // "object" typeof function(){} // "function" typeof 2 //"number" typeof "" //"string" typeof true //"boolean" typeof undefined //"undefined" typeof Symbol(2) // "symbol"

typeof 无法区分null 数组和对象,通常我们会区分判断Array和Object

有时会用instanceof 来判断是不是一个对象的实例子

[] instanceof Array // true 这种方法可以判断数组,不能区分对象 [] instanceof Object // true null instanceof Object // false 也不能区分null

下面介绍一种方法,对每一种数据类型都实用。

阅读全文

本文共计603个文字,预计阅读时间需要3分钟。

toString.call()如何判断各种数据类型的类型?

判断数据类型的方法有很多。我们常用的有`typeof`,但这个方法有一定的局限性。例如:

- `typeof null` 返回 `object`- `typeof []` 返回 `object`- `typeof {}` 返回 `object`- `typeof function()`{} 返回 `function`- `typeof 2` 返回 `number`

这些例子展示了`typeof`的一些局限性。

大家都知道判断数据类型的方法有很多。我们常用的有typeof但是,这个方法有一定的局限性。

typeof null // "object" typeof [8] // "object" typeof {} // "object" typeof function(){} // "function" typeof 2 //"number" typeof "" //"string" typeof true //"boolean" typeof undefined //"undefined" typeof Symbol(2) // "symbol"

typeof 无法区分null 数组和对象,通常我们会区分判断Array和Object

有时会用instanceof 来判断是不是一个对象的实例子

[] instanceof Array // true 这种方法可以判断数组,不能区分对象 [] instanceof Object // true null instanceof Object // false 也不能区分null

下面介绍一种方法,对每一种数据类型都实用。

阅读全文