直接po图和代码
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>javascript中var关键字以及全局变量和局部变量知识点</title>
<link rel="stylesheet" type="text/css" href="inputAndDiv.css">
</head>
<body style="background-color: #CCE8CF;">
<h3 style="color: Maroon;">javascript中var关键字以及全局变量和局部变量知识点</h3>
</body>
<script type="text/javascript">
// console.log(hometown);//hometown is not defined
function fun1(){
//在函数中没有使用var关键字定义的变量是全局变量
hometown = '江西省赣州市于都县';
//结果为hometown=江西省赣州市于都县
console.log('hometown=' + hometown);
}
fun1();
console.log(hometown); //结果为江西省赣州市于都县
console.log(window.hometown);//结果为江西省赣州市于都县
// console.log(age);//报错age is not defined
function fun2(){
//在函数中使用var关键字定义的变量是局部变量
var age = 19;
console.log('age=' + age);//age=19
}
fun2();
// console.log(age); //报错age is not defined
console.log(window.age); //结果为undefined
//在if中
if(true){
//在if中使用了var关键字定义变量
var address = '于都县渡江大道6666号';
//在if中没有使用var关键字定义变量
hobby = '玩魔方';
//结果为***于都县渡江大道6666号 ***玩魔方
console.log('***' + address, '***' + hobby);
}
//address变量和hobby变量,花括号外都可以访问到
console.log(address, hobby);//结果为于都县渡江大道6666号 玩魔方
console.log(window.address, window.hobby);//结果为于都县渡江大道6666号 玩魔方
//在if中
if(66 < 88){
//在if中使用了var关键字定义变量
var address2 = '于都县渡江大道888888号';
//在if中没有使用var关键字定义变量
hobby2 = '耍耍魔方挺有意思';
//结果为***于都县渡江大道888888号 ***耍耍魔方挺有意思
console.log('***' + address2, '***' + hobby2);
}
//address2变量和hobby2变量,花括号外都可以访问到
//结果为于都县渡江大道888888号 耍耍魔方挺有意思
console.log(address2, hobby2);
//结果为于都县渡江大道888888号 耍耍魔方挺有意思
console.log(window.address2, window.hobby2);
</script>
</html>