Apress ProJavaScriptTechniques
The first way of checking the type of an object is by using the obvious-sounding typeof operator.
- // 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(",");
- // 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<o:p></o:p> |
typeof Variable<o:p></o:p> |
Variable.constructor<o:p></o:p> |
|
{ an: “object” }<o:p></o:p> |
object<o:p></o:p> |
Object<o:p></o:p> |
|
[ “an”, “array” ]<o:p></o:p> |
array<o:p></o:p> |
Array<o:p></o:p> |
|
function(){}<o:p></o:p> |
function<o:p></o:p> |
Function<o:p></o:p> |
|
“a string”<o:p></o:p> |
string<o:p></o:p> |
String<o:p></o:p> |
|
55<o:p></o:p> |
number<o:p></o:p> |
Number<o:p></o:p> |
|
true<o:p></o:p> |
boolean<o:p></o:p> |
Boolean<o:p></o:p> |
|
new User()<o:p></o:p> |
object<o:p></o:p> |
User<o:p></o:p> |
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.
- // 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] );
- }
- }
本文介绍了JavaScript中两种类型检查的方法:使用typeof操作符和constructor属性。通过示例展示了如何确保变量类型正确,以及如何严格检查函数参数类型。

被折叠的 条评论
为什么被折叠?



