1、变量
变量保存的数据可以在需要时设置,更新或提取。赋值给变量的值都有对应的类型。JavaScript的类型有数、字符串、布尔值、函数、对象,还有undefined和null,以及数组、日期和正则表达式
1.1、变量作用域
作用域是指,在编写的算法函数中,我们能访问变量(在使用函数作用域时,也可以是一个函数)的地方。有局部变量和全局变量两种。
全局变量
1 2 3 4 5 6 7
| var a = 'global'; console.log(a); function test(){ console.log(a); }
test();
|
局部变量
1 2 3 4 5 6 7
| function test(){ var a = 1; console.log(a) } 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); console.log(myFunction());
console.log(myOtherVariable); console.log(myOtherFunction()); console.log(myOtherVariable);
|