1、变量

变量保存的数据可以在需要时设置,更新或提取。赋值给变量的值都有对应的类型。JavaScript的类型有字符串布尔值函数对象,还有undefinednull,以及数组日期正则表达式

1.1、变量作用域

作用域是指,在编写的算法函数中,我们能访问变量(在使用函数作用域时,也可以是一个函数)的地方。有局部变量全局变量两种。

全局变量

1
2
3
4
5
6
7
var a = 'global';
console.log(a); //global
function test(){
console.log(a);
}

test(); //global

局部变量

1
2
3
4
5
6
7
function test(){
var a = 1;
console.log(a) // 1
}
console.log(a); // 报错
test();
console.log(a); // 报错

例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
var myVariable = 'global';
myOtherVariable = 'global';

function myFunction(){
var myVariable = 'local';
return myVariable;
}

function myOtherFunction(){
myOtherVariable = 'local';
return myOtherVariable;
}

console.log(myVariable); // 输出 global,因为它是一个全局变量
console.log(myFunction()); //输出 local,因为myVariable是在myFunction函数中声明的局部变量,所以作用域仅在myFunction

console.log(myOtherVariable); //输出 global,这里引用的是初始化的全局变量myOtherVariable
console.log(myOtherFunction()); //输出 local,在myOtherFunction里,因为没有使用var 关键字修饰,所以这里引用的是全局变量myOtherVariable,并将其复制为local
console.log(myOtherVariable); //输出 local 因为在myOtherFunction里修改了myOtherVariable的值