2006-12-28
The way of checking the type of an object
关键字: javascriptApress ProJavaScriptTechniques
The first way of checking the type of an object is by using the obvious-sounding typeof operator.
js 代码
- // Check to see if our number is actually a string
- if ( typeof num == "string" )
- // If it is, then parse a number out of it
- num = parseInt( num );
- // Check to see if our array is actually a string
- if ( typeof arr == "string" )
- // If that's the case, make an array, splitting on commas
- arr = arr.split(",");
js 代码
- // Check to see if our number is actually a string
- if ( num.constructor == String )
- // If it is, then parse a number out of it
- num = parseInt( num );
- // Check to see if our string is actually an array
- if ( str.constructor == Array )
- // If that's the case, make a string by joining the array using commas
- str = str.join(',');
|
Variable |
typeof Variable |
Variable.constructor |
|
{ an: “object” } |
object |
Object |
|
[ “an”, “array” ] |
array |
Array |
|
function(){} |
function |
Function |
|
“a string” |
string |
String |
|
55 |
number |
Number |
|
true |
boolean |
Boolean |
|
new User() |
object |
User |
Strict typechecking can help in instances where you want to make sure that exactly the right number of arguments of exactly the right type are being passed into your functions.
js 代码
- // Strictly check a list of variable types against a list of arguments
- function strict( types, args ) {
- // Make sure that the number of types and args matches
- if ( types.length != args.length ) {// If they do not, throw a useful exception
- throw "Invalid number of arguments. Expected " + types.length +
- ", received " + args.length + " instead.";
- }
- // Go through each of the arguments and check their types
- for ( var i = 0; i < args.length; i++ ) {
- //
- if ( args[i].constructor != types[i] ) {
- throw "Invalid argument type. Expected " + types[i].name +
- ", received " + args[i].constructor.name + " instead.";
- }
- }
- }
- // A simple function for printing out a list of users
- function userList( prefix, num, users ) {
- // Make sure that the prefix is a string, num is a number,
- // and users is an array
- strict( [ String, Number, Array ], arguments );
- // Iterate up to 'num' users
- for ( var i = 0; i < num; i++ ) {
- // Displaying a message about each user
- print( prefix + ": " + users[i] );
- }
- }
- 11:06
- 浏览 (860)
- 评论 (0)
- 分类: javascript
- 相关推荐
发表评论
- 浏览: 91618 次

- 详细资料
搜索本博客
最近加入圈子
最新评论
-
Tapestry5-如何在根目录下 ...
o,是我看的不仔细。不过我都是放在class相对应的资源包中。
-- by KorbenZhang -
Tapestry5-如何在根目录下 ...
文章提到的是组件类的模板,页面类默认是在根目录的。
-- by tapestry -
Tapestry5-如何在根目录下 ...
过时了,T5已经把tml文件放在根目录了。
-- by KorbenZhang -
Tapestry5开发系列:如何 ...
我删掉了依赖,加了servlet还是不行,jetty就是不起来,说没找到logg ...
-- by leegorous -
Tapestry5每日播报(20080 ...
非常支持.
-- by biaoming






评论排行榜