Type checking

// 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(",");



The use of the typeof statement helps to lead us into the topic of type-checking. Since

JavaScript is (currently) a dynamically typed language, this proves to be a very useful and

important topic. There are a number of different ways to check the type of a variable; we’re

going to look at two that are particularly useful.

The first way of checking the type of an object is by using the obvious-sounding typeof

operator. This utility gives us a string name representing the type of the contents of a variable.

This would be the perfect solution except that for variables of type object or array, or a custom

object such as user, it only returns object, making it hard to differentiate between all objects.

The second way of checking the type of an object is by referencing a property of all

JavaScript objects called constructor. This property is a reference to the function used to

originally construct this object.

// 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(',');



Table 2-1 shows the results of type-checking different object types using the two differ

methods that I’ve described. The first column in the table shows the object that we’re tryin

find the type of. The second column is the result of running typeof Variable (where Variabl

the value contained in the first column). The result of everything in this column is a string.

Finally, the third column shows the result of running Variable.constructor against the objec

contained in the first column. The result of everything in this column is an object.

Table 2-1. Type-Checking Variables

Variable typeof    Variable     Variable.constructor

{ an: “object” }   object       Object

[ “an”, “array” ]  object       Array

function(){}       function     Function

“a string”         string       String

55                 number       Number

true               boolean      Boolean

new User()         object       User

转载于:https://www.cnblogs.com/coolicer/archive/2011/10/17/2215137.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值