Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[js] 2. JavaScript 中如何检测一个变量是一个 String 类型? #171

Open
qiilee opened this issue Sep 29, 2019 · 2 comments
Open
Labels

Comments

@qiilee
Copy link
Member

qiilee commented Sep 29, 2019

答案:三种方法(typeof、constructor、Object.prototype.toString.call())

解析:

①typeof

typeof('123') === "string" // true

typeof '123' === "string" // true


②constructor

'123'.constructor === String // true


③Object.prototype.toString.call()

Object.prototype.toString.call('123') === '[object String]' // true
@qiilee qiilee added the JS label Sep 29, 2019
@huixu123
Copy link

题目问的是如何检测一个String 类型。这里指的应该是由构造函数String生成的实例对象的类型。
let str = new String('1')
typeof(str) // object
这时候用typeof 是无法判断的

@Hillkinsh
Copy link

漏了一种,instanceof

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants