JS中如何判断一个变量是否已经声明?

JavaScript014

JS中如何判断一个变量是否已经声明?,第1张

//var va

//var va = null

//var va = 'xxxx'

try{

// 已经声明

// 判断是否已经定义

if (va === undefined){

// 不能使用 ==,因为当 "var va = null"时 被判定为未定义是错误的。

//if (typeof va === 'undefined'){ // 这种方式也是不可取的。

// 未定义

window.console &&console.log("变量未定义.")

}else {

// 已经定义了,可能为null

window.console &&console.log("变量已定义.")

}

} catch(e){

// va 未声明

window.console &&console.log("变量未声明,")

}

判断一个值是否未定义,就是判断值是否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为数组

}