js判断变量是否未定义的代码

JavaScript010

js判断变量是否未定义的代码,第1张

例如:

if(!myVar01)alert("发生错误")

//

该代码直接发生异常,因为变量myVar01没有申明

if("undefined"

==

typeof

myVar01)alert("发生错误")

//

这样写才不至于发生异常

而:

var

myVar01

if(undefined

==

myVar01)alert("发生错误")

//

该代码会正确运行

if("undefined"

==

typeof

myVar01)alert("发生错误")

//

该代码同样会正确运行

结论:我们采用下面的方式来保证万无一失

if("undefined"

==

typeof

myVar01)alert("发生错误")

//

该代码同样会正确运行

当然判断数据的有效性远远不只这些,还有对null的判断,数字是否大道越界.

实际应用:

downlm有的页面我们不定义,但有的页面定义了,就可以需要这样的判断方法,没有定义的就不执行。

if("undefined"

!=

typeof

downlm){

if(downlm=="soft"){

document.write('成功')

}

}

经测试完美。

判断一个值是否未定义,就是判断值是否undefined

可以通过typeof()这个方法来获取值的类型

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

var a

if(typeof(a)==="undefined"){

//a为undefined类型

}

a = 123

if(typeof(a)==="number"){

//a为number类型

}

a={}

if(typeof(a)==="object"){

//a为object类型

}

a="abc"

if(typeof(a)==="string"){

//a为string类型

}

a=true

if(typeof(a)==="boolean"){

//a为boolean类型

}

a=function(){}

if(typeof(a)==="function"){

//a为function类型

}

a=[]

if(typeof(a)==="object"){

//值为数组的时候,typeof返回也是"object"

}

要判断值是否为数组,可以通过instanceof方法,判断一个值是否为另一个值的实例

a=[]

if(a instanceof Array){

//a为数组

}