Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
490 views
in Technique[技术] by (71.8m points)

javascript - 获得Javascript变量类型的更好方法?(Better way to get type of a Javascript variable?)

Is there a better way to get the type of a variable in JS than typeof ?

(有没有比typeof更好的方法来获取JS中的变量类型?)

It works fine when you do:

(当您这样做时,它可以正常工作:)

> typeof 1
"number"
> typeof "hello"
"string"

But it's useless when you try:

(但是当您尝试以下操作时,它是没有用的:)

> typeof [1,2]
"object"
>r = new RegExp(/./)
/./
> typeof r
"function"

I know of instanceof , but this requires you to know the type beforehand.

(我知道instanceof ,但这需要您事先知道类型。)

> [1,2] instanceof Array
true
> r instanceof RegExp
true

Is there a better way?

(有没有更好的办法?)

  ask by Aillyn translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Angus Croll recently wrote an interesting blog post about this -

(Angus Croll最近写了一篇有趣的博客文章-)

http://javascriptweblog.wordpress.com/2011/08/08/fixing-the-javascript-typeof-operator/

(http://javascriptweblog.wordpress.com/2011/08/08/fixing-the-javascript-typeof-operator/)

He goes through the pros and cons of the various methods then defines a new method 'toType' -

(他介绍了各种方法的优缺点,然后定义了一个新方法“ toType”-)

var toType = function(obj) {
  return ({}).toString.call(obj).match(/s([a-zA-Z]+)/)[1].toLowerCase()
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...