Correcting teacher:天蓬老师
Correction status:qualified
Teacher's comments:js中一切皆对象, 慢慢品
<script></script>
标签中<script src="1.js"></script>
标签的src属性引入js文件。如果script标签添加了src属性,将忽略标签中的内容。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>JAVASCRIPTE</title>
</head>
<body>
<script>
document.getElementById("title3").style.color = "green";
</script>
<h2 id="title1">JS代码演示1</h2>
<h2 id="title2">JS代码演示2</h2>
<h2 id="title3">JS代码演示3</h2>
<!--因HTML代码的执行顺序问题,把js代码放<h2>之后,否则不生效-->
<script>
document.getElementById("title1").style.color = "red";
</script>
<script src="1.js"></script>
</body>
</html>
1.js
document.getElementById("title2").style.color = "blue";
效果图:title3因为js代码在前,没生效
var
关键字,如: var name='小王';
es6版本也可以使用let
和const
定义变量和常量name
和Name
是定义了两个不同的变量
<script>
var name;
name = 10; //数值型
name = "abc"; //字符型
console.log(Name);//ReferenceError: Name is not defined /Name未定义
</script>
<script>
var user;
user = 10; //数值型
user = "abc"; //字符型
user = true; //bolean
user = null;//null,一般表示空对象
user = undefined;//undefined,用于表示非对象类型的空值
user = ['21','dsj',23,null];//数组
user = { name: "admin",phone:"524566" };//对象
user = function(a,b){return a*b;}//函数
</script>
<script>
var user;
user = "admin";
//if else
if (user == "admin") {
console.log("欢迎您!" + user);
} else if (user == "guest") {
console.log("游客您好!");
} else {
console.log("您无此权限");
}
//switch 与if else一样的效果,但是更直观,适合多分支
switch (user) {
case "admin":
console.log("欢迎您!" + user);
break;//满足条件跳出当前,不执行后面的case
case "guest":
console.log("游客您好!");
break;
default:
console.log("请注册!");
}
</script>
<script>
var sum = 0;
//满足条件执行
for (var i = 10; i > 0; i--) {
sum += i;
}
console.log(sum); //55
var i = 1;
//满足条件后再执行
while (i < 11) {
sum -= i;
i++;
}
console.log(sum); //0
//执行一次后,再判断条件是否执行下次
do {
sum -= i;
i++;
} while (i < 11);
console.log(sum); //-11
</script>
<script>
function buy(goods) {
console.log("今天买了2个" + goods);
}
function Buy(goods) {
console.log("今天买了1个" + goods);
}
Buy("大西瓜"); //今天买了1个大西瓜
buy("大西瓜"); //今天买了2个大西瓜
</script>
// 创建一个对象
var student = {
name: "小明",
sex: "男",
grade: "一年级",
study: function (name, course) {
return name + "这节课学习了" + course;
},
};
//访问对象的属性和方法,对象名.属性名/方法名
console.log(student.name); //小明
console.log(student.study(student.name, "语文")); //小明这节课学习了语文
//js系统内置对象
var name = "jack chen";
//字符串对象
console.log(name.length); //字符串长度
console.log(name.search("a", name)); //查找a在字符串中的位置
//数组对象
var arr = new Array("a", 1, "5");
console.log(arr[0]); //a
console.log(arr.length);//3