JavaScript基础

JavaScript1 JavaScript概述2 JavaScript基础语法2.1 引入方式2.2 数据类型2.3 字符串类型2.4 对象类型2.5 数组类型2.6 流程控制2.6 Map和Set集合2.7 函数定义2.8 变量作用域2.9 方法定义2.10 Data对象2.11 JSON对象3 JavaScript面向对象3.1 原型继承3.2 Class继承3.3 原型链4 JavaScript操作BOM对象5 JavaScript操作DOM节点5.1 获取DOM节点5.2 更新DOM节点5.3 删除DOM节点5.4 创建DOM节点5.5 表单操作5.6 表单验证6 JQuery简单入门6.1 JQuery事件
JavaScript
1 JavaScript概述
ECMAScript
JavaScript的一个标准
- ES5:全部浏览器支持
- ES6:开发常用的版本
浏览器控制台使用
简单介绍

控制台

输入指令
调试

设置断点,然后刷新网页进行调试
2 JavaScript基础语法
2.1 引入方式
1.内部script标签
xxxxxxxxxx31<script>2    alert('hello world!')3</script>2.外部引入
xxxxxxxxxx11<script src="js/script.js"></script>快速使用:
xxxxxxxxxx221<html lang="en">3<head>4    <meta charset="UTF-8">5    <title>JavaScript</title>6
7    <!--script标签,写JavaScript语句8    不要使用自闭和 成对出现9    -->10<!--    <script>-->11<!--        alert('hello world!')-->12<!--    </script>-->13
14    <!--外部引入 默认javaScript不用显式定义-->15    <script src="js/script.js"></script>16
17</head>18<body>19
20<!--Js也会插入到body尾部-->21</body>22</html>xxxxxxxxxx11alert('hello world!')2.2 数据类型
number(不区分小数,整数)
xxxxxxxxxx6112     //整数212.12  //小数31.22e3 //科学计数4-12    //负数5Nan    //Not a number6Infinity //无限大字符串
xxxxxxxxxx31'abc'2"abc"3//还有转义字符等逻辑运算
xxxxxxxxxx31&&  //与2||  //或3!  //非比较运算
xxxxxxxxxx21==  //等于 数值相等(类型不同也反返回ture)2=== //绝对等于 类型相同,数值相同    判断是否为NaN使用isNaN()判断
NULL与undefined
- null 空
- undefined 未定义
快速使用数据类型
xxxxxxxxxx331//1.定义变量2/*定义区分大小写*/3var num = 35;4
5//2.条件控制6if (num>30&&num<40){7    alert("30~40,num="+num);8}else{9    alert("other")10}11/*console.log()打印变量 浏览器控制台*/12
13console.log(1=="1");      //true14console.log(1==="1");     //false 绝对等于15console.log(NaN===NaN);   //false16console.log(isNaN(NaN));  //true  判断为NaN的方法17console.log(1/3===1-2/3); //false 由于损失精度,小数不能使用等于判断18console.log(Math.abs(1/3-(1-2/3))<0.00000001) //小数的近似的等于判断19
20var arr = [1,2,3,null,"hello",true] //数组允许不同类型21
22arr1 = new Array(1,2,3,null,"hello",true)23
24console.log(arr[4],arr[5],arr[6])25
26/*创建对象,类似Python字典*/27var person ={28    name:"ZhangSan",29    age:3,30    tags:["js","java","web"]31}32
33console.log(person.name)2.3 字符串类型
xxxxxxxxxx271'use strict'2console.log("a");3/*输出特殊使用转义\'*/4
5console.log("a\'");6console.log("abc\nabc");7console.log("\u4e2d"); //unicode8console.log("\x41")    //Ascll9
10/*多行字符*/11let msg = `hello12        你好13        再见`;14console.log(msg);15
16/*模板*/17let name = "ZhangSan";18let age= 3;19
20msg = `你好,${name},今年${age}岁`;21console.log(msg);22
23/*字符串长度*/24console.log(msg.length);25console.log(msg[0]);//类似字符串数组26console.log(msg.toUpperCase());//大写27console.log(msg.substring(1,4));//类似切片2.4 对象类型
xxxxxxxxxx391"use strict"2/*对象*/3let person = {4    name: "ZhangSan",5    age: 3,6    email: "12345@qq.com",7    score: 08};9
10console.log(person.name);11
12/*对象赋值*/13person.name = "LuoXian";14
15/*动态删除属性*/16delete person.score;17console.log(person);18
19/*动态添加属性*/20person.sex = "man";21console.log(person);22
23/*判断值是否在对象中*/ //true24if ('age' in person){ 25    console.log(true);26}27/*可以找到继承的属性*/ //true28if ('toString' in person){29    console.log(true);30}31/*判读是否是对象自身属性*/ //true32if (person.hasOwnProperty("age")){33    console.log(true);34}35if (person.hasOwnProperty("toString")){ //false 这里继承的不是自身属性36    console.log(true);37}else {38    console.log(false);39}2.5 数组类型
1'use strict'2/*数组*/3let arr = [1,2,3,4,5,6];4console.log(arr);5console.log(arr.length); //66/*动态改变长度*/7arr.length = 10;8console.log(arr);9console.log(arr[8]); //undefined10//减少长度会损失数据11arr.length = 4;12console.log(arr);13
14/*indexOf 字符串和数字类型不同*/15arr = [1,2,"1","2"];16console.log(arr.indexOf(2)); //117console.log(arr.indexOf("2")); //318
19/*slice数组切片*/20console.log(arr.slice(1,3)); //arr[1,3]  [2,"1"]21
22/*push(),pop()*/23console.log(arr.push("a","b")); //在后面插入24console.log(arr);25
26console.log(arr.pop()); //弹出最后面27console.log(arr);28
29/*unshift(),shift()*/30console.log(arr.unshift("a","b")); //在前面插入31console.log(arr);32
33console.log(arr.shift()); //弹出最前面34console.log(arr);35
36/*sort()*/37let arr1 = ["b","a","c"];38arr1.sort(); //排序39console.log(arr1); //["a","b","c"]40
41/*元素反转*/42arr1.reverse();43console.log(arr1); //["c","b","a"]44
45/*拼接 返回新数组*/ //注意是返回不是修改46console.log(arr1.concat(["1","2","3"]));//["a","b","c","1","2","3"]47
48/*连接符join*/49console.log(arr1.join('-')); //c-b-a50
51/*多维数组*/52let arr2 = [[1,2],[3,4],["5","6"]];53console.log(arr2);54console.log(arr2[1][1]) //42.6 流程控制
xxxxxxxxxx331'use strict'2/*if判断*/3let age = 3;4if (age>3){5    alert("haha");6}else {7    alert("ku");8}9
10/*while循环*/11while (age<100){12    age = age + 1;13    console.log(age);14}15
16/*for循环*/17for (let i = 0; i < 100; i++) {18    console.log(i);19}20
21/*数组循环*/22let arr = [12,41,436,12,4568,12]23arr.forEach(function (value){24    console.log(value);25})26
27for (let num in arr){28    console.log(arr[num]);29}30//推荐使用31for (let num of arr){32    console.log(num);33}2.6 Map和Set集合
xxxxxxxxxx181'use strict'2/*map*/3let map = new Map([['ZhangSan',100],['LiSi',90],['LiHua',0]]);4/*取值 key -> value*/5console.log(map.get('ZhangSan')); //1006map.set("admin",123456); //添加元素7console.log(map);8map.delete('LiSi'); //删除元素9console.log(map);10
11/*set 无序不重复集合*/12let set = new Set([1,2,2,3,3,3,4]);13console.log(set); //1,2,3,414set.add(5);15console.log(set);16set.delete(4);17console.log(set);18console.log(set.has(2)); //ture2.7 函数定义
xxxxxxxxxx401'use strict'2/*定义方式二:匿名函数3var abs = function(x){4    if (x<=0){5        return -x;6    }7    return x;8}9* */10
11/*JS可以传递任意个参数,也可以不存在参数*/12function abs(x){13    if (typeof x !== 'number'){ //不是数字14        throw 'Not a Number'15    }16    if (x<=0){17        return -x;18    }19    return x;20}21
22/*通过arguments可以获取所有的参数*/23function a(x){24    for (let argument of arguments) {25        console.log(argument);26    }27}28
29/*rest只能放在最后面,加...*/30function b(a,b,rest){31    console.log("a="+a);32    console.log("b="+b);33    console.log("rest="+rest);34}35
36console.log(abs(-100));37a(1,2,3,4,5,6,7,8,9);38b(1);         // a=1 b=undefined rest = 39b(1,2);       // a=1 b=2 rest = 40b(1,2,4,5,6); // a=1 b=2 rest=4,5,62.8 变量作用域
x
1'use strict'2/*var在函数体内声明吗,函数体外不能使用(可以使用闭包)*/3//定义全局变量4var y = 1;5
6function a(){7    var x = 1;8    x = x + 1;9    console.log(y); //110}11
12/*js函数内局部变量 会自动放在最前面进行定义 防止错误引用不报错 手动将所有变量定义放在函数最前面*/13function b(){14    var a = b + "1";15    console.log(a); //输出undefined1 b这时已经存在了 但是没赋值16    var b = "2";17}18
19//这里无法使用function a 中的 x (函数内的var)20a();21b();22
23var oldAlert = window.alert;24window.alert("123") //正常输出25window.alert = function (){26
27}28alert("456") //alert已经被替换了无法使用29window.alert = oldAlert;30alert("567") //正常输出31
32/*任何变量(函数也可以视为变量),由内向外查找,window最外层*/33/*所有全局变量会绑定到window,不同文件会导致全局命名冲突 建议使用以下方式*/34/*唯一全局变量*/35var App = {}; //只在本文件内使用36
37//定义全局变量38App.name = "ZhangSan";39App.add = function (a,b){40    return a + b;41}42
43function c(){44    for (var i = 0; i < 100; i++) {//let45        console.log(i);46    }47    console.log(i);//出了作用域依然能使用,建议用let定义局部变量,防止错误产生48}49c();50
51/*ES6 const 常量*/ //ES5没有2.9 方法定义
x
1//定义对象2let person = {3    name: "ZhangSan",4    age: 10,5    //定义方法 方式16    birth: function (){7        let now = new Date().getFullYear();8        return now - this.age;9    }10}11
12let student = {13    name: "ZhangSan",14    age: 11,15    //定义方法 方式216    birth:getBirth17}18
19/*方法放在外面*/20//不能直接调用此函数,这里的this不会直指向student,所以使用前要委派this指向的对象,再进行调用21function getBirth(){22    let now = new Date().getFullYear();23    return now - this.age;24}25
26console.log(person.birth());27console.log(student.birth());28//console.log(getBirth()); //NaN29let birth = getBirth.apply(student,[]); //委派this指向的对象30console.log(birth);2.10 Data对象
121'use strict'2let now = new Date();3console.log(now);4console.log(now.getFullYear()); //年5console.log(now.getMonth()); //月 0~116console.log(now.getDate()); //日期7console.log(now.getDay()); //星期8console.log(now.getHours());//小时9console.log(now.getTime()); //时间戳10console.log(now.toLocaleString()); //本地时间11
12console.log(new Date(now.getTime())); //时间戳获得当前时间 (全世界统一)2.11 JSON对象
xxxxxxxxxx151"use strict"2/*对象*/3let person = {4    name: "ZhangSan",5    age: 3,6    email: "12345@qq.com",7    score: 08};9
10/*对象转换为json字符串*/11let json = JSON.stringify(person);12console.log(json); //输出JSON字符串13
14let user = JSON.parse("{\"age\":3,\"name\":\"ZhangSan\",\"score\":0}");15console.log(user); //通过JSON字符串输出对象3 JavaScript面向对象
3.1 原型继承
一个对象的原型为另一个对象,这个对象就会有原型对象的属性(但是这里的原型继承是类似类嵌套的关系,原型对象相当于嵌套进当前对象,使得当前对象可以使用原型的方法)
x
1"use strict"2/*对象*/3let person = {4    name: "ZhangSan",5    age: 3,6    email: "12345@qq.com",7    score: 0,8    run: function (){9        console.log(this.name+" run.");10    }11};12
13let XiaoMing = {14    name: "XiaoMing"15}16
17/*XiaoMing原型是person*/18XiaoMing.__proto__ = person;19
20console.log(XiaoMing.run());3.2 Class继承
ES6新特性,Class的机制与Java中的类似(但是JS的本质还是把Class转化成原型继承)
xxxxxxxxxx1"use strict"2/*class ES6规范*/3/*对象*/4class person{5    constructor(name) {6        this.name = name;7    }8
9    hello(){10        alert('hello')11    }12}13
14class student extends person{15    constructor(name,grade) {16        super(name);17        this.grade = grade;18    }19
20    getGrade(){21        alert(this.grade);22    }23}24
25let XiaoMing = new person("XiaoMing");26console.log(XiaoMing.name);27XiaoMing.hello();28
29let XiaoHong = new student("XiaoMing",6);30XiaoHong.hello();31XiaoHong.getGrade();3.3 原型链
简单理解原型与原型链的概念
1. 函数 与 prototype
定义一个Person函数:
x
1function Person(age){2    this.age = age3}4//打印Person函数的prototype5console.log(Person.prototype)6Person.prototype.name = "Person";//添加一个属性会发现函数是有原型对象的 Person函数存在一个Person.prototype对象,而这个函数就作为这个对象的构造函数,形成了如下的关系:

2. 原型继承
使用Person构造器创建一个对象ZhangSan
xxxxxxxxxx11let ZhangSan = new Person(1);这时就有了以下的关系:
.png)
给ZhangSan增加name属性:
x
1ZhangSan.name = "ZhangSan";查看ZhangSan的结构:

发现ZhangSan的原型对象中同时存在name属性,如果ZhangSan没有name属性就会向下找到ZhangSan原型中name = "Person",所以可以看出原型是类似嵌套的方式继承的(或者说类似子类重写父类的属性)
3. 原型链
继续往下查看原型对象的原型
x
1/*原型对象的原型*/2console.log(Person.prototype.__proto__ === Object.prototype);  //true 对象3console.log(Person.prototype.__proto__.constructor === Object);//true4console.log(Object.prototype.__proto__ === null)               //没有原型,可以停止检查了通过上面三条判断语句得出了下面的结构:
.png)
可以看出Object的原型对象没有原型了,指向了NULL这时就可以停止检查了,这就是我们创建对象的原型链的结构了
测试代码:
x
1'use strict'2function Person(age){3    this.age = age4}5console.log(Person.prototype)6Person.prototype.name = "Person"; //每个函数都有一个prototype属性,指向函数的原型对象7let ZhangSan = new Person(1);     //Person相当于构造函数 做为Person.prototype实例原型的构造函数8console.log(ZhangSan.name);       //"Person"9console.log(ZhangSan)             //通过Person构造函数创建的对象10console.log(ZhangSan.__proto__ === Person.prototype);  //true ZhangSan的原型对象是Person.prototype11ZhangSan.name = "ZhangSan";12console.log(ZhangSan);13/*ZhangSan对象的结构:14*ZhangSan {age: 1, name: 'ZhangSan'}15*age: 116*name: "ZhangSan"  //没有此属性就会向下寻找到Person.prototype.name  张三的名字17*__proto__: Person.prototype18*  name: "Person" //Person的名字19*  constructor: ƒ Person(age) //Person.prototype.constructor === Person20*  __proto__: Object21* */22
23/*原型对象的原型*/24console.log(Person.prototype.__proto__ === Object.prototype);//true 对象25console.log(Person.prototype.__proto__.constructor === Object);//true26console.log(Object.prototype.__proto__ === null)//没有原型,可以停止检查了4 JavaScript操作BOM对象
BOM:浏览器对象模型
Window
浏览器窗口
x
1>window.innerHeight2<8313>window.innerWidth4<7295>window.outerHeight6<11277>window.outerWidth8<1690Navigator
navigator,封装浏览器信息
xxxxxxxxxx11>navigator.appName2<'Netscape'3>navigator.appVersion4<'5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.55 Safari/537.36 Edg/96.0.1054.34'5>navigator.platform6<'Win32'navigator,会被人为修改
screen
屏幕属性:
xxxxxxxxxx11screen.width225603screen.height41440location
代表当前页面的URL信息,可以用来设置重定向
5 JavaScript操作DOM节点
5.1 获取DOM节点
html:
x
1<div id="main">2    <h1>标题</h1>3    <p id="p1">第一段</p>4    <p class="p2">第二段</p>5</div>js:
x
1'use strict'2let h1 = document.getElementsByTagName("h1");  //获取标题 对象3let p1 = document.getElementById("p1"); //获取第一段 对象4let p2 = document.getElementsByClassName("p2"); //获取第二段 对象5let main = document.getElementById("main");6
7console.log(main.children);//父节点下的所有子节点8// main.firstChild;9// main.lastChild;获取到了DOM节点就能操作DOM节点了
5.2 更新DOM节点
操作DOM节点,动态添加文本与样式
html:
xxxxxxxxxx31<div id="main">2
3</div>js:
x
1'use strict'2let main = document.getElementById("main");3main.innerText="hello world";//修改文本的值4main.innerHTML="<strong>hello world</strong>\n"//插入HTML5main.style.color="red";//操作样式6main.style.fontSize="20px"5.3 删除DOM节点
html:
xxxxxxxxxx51<div id="main">2    <h1>标题</h1>3    <p id="p1">第一段</p>4    <p class="p2">第二段</p>5</div>js:
x
1'use strict'2//不能自己删除自己3let p1 = document.getElementById("p1");4let main = p1.parentElement;5//通过父节点删除子节点6main.removeChild(p1);5.4 创建DOM节点
html:
61<div id="main">2    <h1>标题</h1>3    <p id="p1">第一段</p>4    <p id="p2">第二段</p>5    <p id="p3">第三段</p>6</div>js:
xxxxxxxxxx1'use strict'2
3//移动已有的标签4let main = document.getElementById("main");5let p1 = document.getElementById("p1");6main.append(p1);//追加到后面7
8/*创建新节点*/9let pNew = document.createElement('p');10pNew.id = "pNew";11pNew.innerText = "java";12pNew.style.color="red"13main.append(pNew);14
15/*创建Script标签*/16let myScript = document.createElement("script");17myScript.setAttribute("type","text/javascript");18myScript.setAttribute("src","test.js");19main.append(myScript);//加入一段JS代码20
21let body = document.getElementsByTagName("body");22body[0].style.backgroundColor = "yellow";test.js:
61/*创建新节点*/2let pNew2 = document.createElement('p');3pNew2.id = "pNew2";4pNew2.innerText = "javaScript";5pNew2.style.color="blue"6main.append(pNew2);5.5 表单操作
html:
111<form action="post">2    <p>3        <span>用户名:</span>4        <input type="text" id="userName" value="123">5    </p>6    <p>7        <span>性别:</span>8        <input type="radio" name="sex" class="sex" value="man" >男9        <input type="radio" name="sex" class="sex" value="woman" checked>女10    </p>11</form>js:
x
1'use strict'2//获取表单文本框都值3let userName = document.getElementById("userName");4let value = userName.value;//得到输入框的值5console.log(value);6
7//判断单选框的选中的元素并且打印 8//通过遍历所有选项用checked的值判断是否被选中9let sexCheck = document.getElementsByClassName("sex");10let Checked;11for (let sexCheckElement of sexCheck) {12    if (sexCheckElement.checked){13        Checked = sexCheckElement.value;14    }15}16console.log(Checked);5.6 表单验证
前端检查的好处:减少服务器压力,但是会被修改代码绕过检查
html:
x
1<!--表单提交绑定事件 检查提价内容2false 提交不通过3true 允许提交4-->5<form action="5%20创建DOM节点.html" method="post" onsubmit="return checked()">6    <p>7        <span>用户名:</span>8        <input type="text" id="userName" name="userName" placeholder="请输入用户名" required>9    </p>10    <p>11        <span>性别:</span>12        <input type="radio" name="sex" class="sex" value="man" >男13        <input type="radio" name="sex" class="sex" value="woman">女14    </p>15    <p>16        <!--直接修改加密密码框的值会看到提交的时候密码变长-->17        <span>密码:</span>18        <input type="password" id="password" placeholder="请输入密码" required><!--name="password" 不作为表单元素提交-->19    </p>20    <!--隐藏加密数据-->21    <input type="hidden" id="md5-pwd" name="password"><!--提交的为隐藏元素-->22    <p>23        <button type="submit" >提交</button>24        <button type="reset">重置</button>25    </p>26</form>js:
x
1'use strict'2function checked(){3    //获取表单文本框都值4    let userName = document.getElementById("userName");5    let NameValue = userName.value;//得到输入框的值6    console.log(NameValue);7
8    if (NameValue.length > 5){9        alert("用户名不能大于5个字符");10        return false;11    }12
13    //判断单选框的选中的元素并且打印14    let sexCheck = document.getElementsByClassName("sex");15    let Checked;16    for (let sexCheckElement of sexCheck) {17        if (sexCheckElement.checked){18            Checked = sexCheckElement.value;19        }20    }21    if (Checked === undefined){22        alert("未选择性别");23        return false;24    }25    console.log(Checked);26    27    //检查密码是否合法28    let pwd = document.getElementById("password");29    let pwdValue = pwd.value;30    if (pwdValue.length>10||pwdValue.length<1){31        alert("密码不能大于10个字符或小于1个字符");32        return false;33    }34
35    /*提交加密密码*/36    let md5Pwd = document.getElementById("md5-pwd");37    md5Pwd.value = md5(pwdValue);  //给隐藏元素value赋值 这是真正提交的值38    console.log(pwdValue);    39
40    /*debug 弹框*/41    alert("提交成功\n"+NameValue+"  "+Checked+"  "+pwdValue+"\n"+md5Pwd.value);42    return true;css:
x
1#password{2    margin-left: 15px;3}4.sex:nth-of-type(1){5    margin-left: 15px;6}7.sex:nth-of-type(2){8    margin-left: 50px;9}10button[type="submit"]{11    width: 100px;12}13button[type="reset"]{14    margin-left: 35px;15    width: 100px;16}17form{18    width: 300px;19    height: 300px;20    margin: 200px auto;21}6 JQuery简单入门
需要下载JQuery并导入
xxxxxxxxxx11<a href="" id="test">屠龙宝刀点击就送</a>2
3<script>4    'use strict'5    /*选择器 和css一样*/ /*添加点击事件*/6    $('#test').click(function() {7        alert("傻宝");8    });9</script>6.1 JQuery事件
获取鼠标位置:
x
1<style>2     body{3         padding: 0;4         margin: 0;5     }6     #div{7         width: 500px;8         height: 500px;9         background: chartreuse;10     }11     #text{12         position: relative;13         font-size: 20px;14         font-weight: bolder;15         left: 210px;16         top: 230px;17     }18</style>19
20<div id="div">21    <span id="text">动我试试</span>22</div>23position: <span id="position"></span>24
25<script>26    'use strict'27    $(function (){28        $("#div").mousemove(function (e){//鼠标移动事件29            $("#position").text("x:"+e.pageX+"  y:"+e.pageY)30        })31    });32</script>
posted on 2021-11-30 19:00 Egoistic_Flowers 阅读(33) 评论(0) 收藏 举报
 
 
         
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号