📦个人主页:楠慧 🏆简介:一个大二的科班出身的,主要研究Java后端开发 ⏰座右铭:成功之前我们要做应该做的事情,成功之后才能做我们喜欢的事
1995 年,NetScape (网景)公司,开发的一门客户端脚本语言:LiveScript。后来,请来 SUN 公司的专家来 进行修改,后命名为:JavaScript。 1996 年,微软抄袭 JavaScript 开发出 JScript 脚本语言。 1997 年,ECMA (欧洲计算机制造商协会),制定出客户端脚本语言的标准:ECMAScript,统一了所有客户 端脚本语言的编码方式。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JS快速入门</title>
</head>
<body>
<button id="btn">点我呀</button>
</body>
</html>
<script>
document.getElementById("btn").onclick=function () {
alert("点我干嘛?");
}
</script>
创建js文件
document.getElementById("btn").onclick=function () {
alert("点我干嘛?");
}
在html中引用外部js文件
<script src="js/my.js"></script>
JavaScript 是一种客户端脚本语言。
组成部分
ECMAScript、DOM、BOM
和 HTML 结合方式
内部方式:<script></script>
外部方式:<script src=文件路径></script>
单行注释
// 注释的内容
多行注释
/*
注释的内容
*/
JavaScript 属于弱类型的语言,定义变量时不区分具体的数据类型。
定义局部变量 let 变量名 = 值;
//1.定义局部变量
let name = "张三";
let age = 23;
document.write(name + "," + age +"<br>");
定义全局变量 变量名 = 值;
//2.定义全局变量
{
let l1 = "aa";
l2 = "bb";
}
//document.write(l1);
document.write(l2 + "<br>");
定义常量 const 常量名 = 值;
//3.定义常量
const PI = 3.1415926;
//PI = 3.15;
document.write(PI);
typeof 用于判断变量的数据类型
let age = 18;
document.write(typeof(age)); // number
if 语句
//if语句
let month = 3;
if(month >= 3 && month <= 5) {
document.write("春季");
}else if(month >= 6 && month <= 8) {
document.write("夏季");
}else if(month >= 9 && month <= 11) {
document.write("秋季");
}else if(month == 12 || month == 1 || month == 2) {
document.write("冬季");
}else {
document.write("月份有误");
}
document.write("<br>");
switch 语句
//switch语句
switch(month){
case 3:
case 4:
case 5:
document.write("春季");
break;
case 6:
case 7:
case 8:
document.write("夏季");
break;
case 9:
case 10:
case 11:
document.write("秋季");
break;
case 12:
case 1:
case 2:
document.write("冬季");
break;
default:
document.write("月份有误");
break;
}
document.write("<br>");**for 循环**
for循环
//for循环
for(let i = 1; i <= 5; i++) {
document.write(i + "<br>");
}
while 循环
//while循环
let n = 6;
while(n <= 10) {
document.write(n + "<br>");
n++;
}
数组的使用和 java 中的数组基本一致,但是在 JavaScript 中的数组更加灵活,数据类型和长度都没有限制。
定义格式
let 数组名 = [元素1,元素2,…];
let arr = [10,20,30];
索引范围
数组长度
数组名.length
for(let i = 0; i < arr.length; i++) {
document.write(arr[i] + "<br>");
}
document.write("==============<br>");
数组高级运算符…
数组复制
//复制数组
let arr2 = [...arr];
//遍历数组
for(let i = 0; i < arr2.length; i++) {
document.write(arr2[i] + "<br>");
}
document.write("==============<br>");
合并数组
//合并数组
let arr3 = [40,50,60];
let arr4 = [...arr2 , ...arr3];
//遍历数组
for(let i = 0; i < arr4.length; i++) {
document.write(arr4[i] + "<br>");
}
document.write("==============<br>");
字符串转数组
//将字符串转成数组
let arr5 = [..."heima"];
//遍历数组
for(let i = 0; i < arr5.length; i++) {
document.write(arr5[i] + "<br>");
}
函数类似于 java 中的方法,可以将一些代码进行抽取,达到复用的效果
定义格式
function 方法名(参数列表) {
方法体;
return 返回值;
}
可变参数
function 方法名(…参数名) {
方法体;
return 返回值;
}
匿名函数
function(参数列表) {
方法体;
}