javascript中var关键字以及全局变量和局部变量知识点

直接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>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值