JavaScript
- JavaScript 是一种轻量级的编程语言。
- JavaScript 是
可插入 HTML 页面
的编程代码。 - JavaScript 插入 HTML 页面后,可由所有的
现代浏览器
执行。 - JavaScript 很容易学习。
1、Quickstart
- demo
<!--内部标签-->
<script>
alert("hello Script!")
</script>
<!--外部引入-->
<script src="js/demo.js" type="text/javascript" charset="utf-8"></script>
2、控制台的使用
console.log(a)
3、数据类型
- let
局部变量建议用
let
来修饰
- 该注意的问题
= //赋值运算符
== //等于(类型不一样,值一样,也会判断为True)
=== //绝对等于(类型一样,值一样,才会为True)
-
NaN===NaN与所有的数值都不相等
-
isNaN(num) 来判断一个数是不是为num
-
浮点数
![image-20210926094218768](JavaScript.assets/image-20210926094218768.png)
- 数组与对象
数组用中括号
[]
对象用大括号
{}
<script type="text/javascript">
var person = {
name:"zyz",
age:10,
class:1,
tags:[1,2,3,4,5,6,"tags"]
}
var arr = [1,2,3,4,5,6,true,null,"hello"]
</script>
3.1、字符串
- 转义字符
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ysALvzne-1632733557317)(JavaScript.assets/image-20210926100417904.png)]
- 多行字符串编写
用飘号引起来
var str = `hello
world
from
string
dialog`
//控制台输出
'hello\n\t\t\tworld\n\t\t\tfrom\n\t\t\tstring\n\t\t\tdialog'
- 模板套用
${var}
var num = 10;
var use_var = `hello world is : ${num}`
//控制台输出
'hello world is : 10'
- 字符串函数的调用
JS
var string = "helloworld"
输出
use_var
'hello world is : 10'
string.length
10
string
'helloworld'
string.indexOf('l')
2
string.lastIndexOf('l')
8
string.substring(1,5)
'ello'
3.2、数组
-
arr.lenth = 原本的大,会扩大容量;如果比原来的小会缩小。
-
slice()
-
push(); pop() 从尾部进行操作
-
unshift(); shift() 从头部进行操作
-
reverse()
-
concat(): 并没有修改原本的数组,只是返回一个新的数组
-
join() 连接符
-
多维数组
3.3、对象
JavaScript中,所有的键都是
字符串
;值是对象
找不到属性的话,就会出现undefined
- 对象属性动态赋值
//原对象
person
{name: 'wsr', age: 18}
//动态添加
person.email = "1324394986qq.com"
'1324394986qq.com'
//输出结果
person
{name: 'wsr', age: 18, email: '1324394986qq.com'}
- 对象属性动态删除
person
{name: 'wsr', age: 18, email: '1324394922@qq.com'}
//动态删除
delete person.email
true
- 判断属性值是否存在对象里
person
{name: 'wsr', age: 18, email: '1324394986qq.com'}
//判断属性 `name`是否存在对象里
'name' in person
true
//因为有继承,所以person有toString方法;判断为true
`toString` in person
true
obj.hasOwnProperty()
//判断对象是否有包含这个东西
//排除其他关系来判断
person.hasOwnProperty('toString')
false
- 所有的key都是字符串
person['name']
'wsr'
3.4、遍历
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Rutmiqtt-1632733557319)(JavaScript.assets/image-20210926110941120.png)]
in是下标
of是值
for(var s of map){
alert("key:"s[0] + “val:” s[1]);
}
3.4、集合
都要new出来
1、Map
<script type="text/javascript">
var map = new Map([[100,"zyz"],
[120,"lyr"],
[200,"wsr"],])
</script>
- 查
map
//结果:Map(5) {100 => 'zyz', 120 => 'lyr', 200 => 'wsr', Array(2) => undefined, 99 => 'fcj'}
map.get(100)
//结果:'zyz'
- 增
map.set(250,"zyz")
- 删
map.delete(250)
- 改
有的就覆盖,没有的就新增
map.set(250,"zyz")
2、Set
无序不重复的集合
var set = new Set([1,2,3,1,1,1,1,1,1]);
- 查
set
//结果:Set(3) {1, 2, 3}
- 增
set.add(4)
//结果:Set(4) {1, 2, 3, 4}
- 删
set.delete(1)
//结果:Set(3) {2, 3, 4}
- 是否存在
set.has(3)
//结果:true
3、Iterator
Set 的遍历
for(let s of map){
console.log(s)
}
Map的遍历
for(let s of map){
console.log(s)
}
for…in
//先获取下标,在通过下标获取值
var arr = [3,4,5,6,7,8,9,10]
for(var num in arr){
console.log(arr[num])
}
4、严格检查模式
需要放在第一行
'use strict'
5、判断类型
typeof var
6、函数
6.1、函数定义的两种方式
//===way1
function abs(x){
if(x>=0){
return x;
}else{
return -x;
}
}
//===way2
var abs2 = function(x){
if(x>=0){
return x;
}else{
return -x;
}
}
6.2、异常
function abs(x){
if(typeof x !== "number"){
throw 'Not a Number'
}
}
效果图
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Nv6t3qaP-1632733557321)(JavaScript.assets/image-20210926132942004.png)]
6.3、arguments
代表传递进来的所有参数,是一个数组!
if(x>=0){
//输出数组长度;并且遍历
console.log(arguments.length)
for(let a in arguments){
console.log("a:" + arguments[a])
}
return x;
}else{
//输出数组长度;并且遍历
console.log("args:" + arguments.length)
for(let a in arguments){
console.log("a:" + arguments[a])
}
return -x;
}
输出结果:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Hum7uzvq-1632733557323)(JavaScript.assets/image-20210926134414989.png)]
6.4、…rest
这是一个专门存放可变参数的数组。它会排除本身传进来的参数,匹配多余的参数
注意:只能写在最后面
<script type="text/javascript">
var abs = function(x,...rest){
if(x>=0){
console.log("rest:" + rest.length)
for(let r in rest){
console.log(">0 rest:" + rest[r])
}
return x;
}else{
console.log("rest:" + rest.length)
for(let r of rest){
console.log("<0 rest:" + r)
}
return -x;
}
}
</script>
6.5、作用域
-
内部可以访问外部的成员变量;反之不行
-
同名变量
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-zfP5OHzp-1632733557325)(JavaScript.assets/image-20210926141003546.png)]
- 变量定义规范
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-CS2RgxfX-1632733557326)(JavaScript.assets/image-20210926141354333.png)]
6.6、全局变量
定义在函数外部,就是属于全局变量
window 存放全局的变量;以及方法
- demo
<script type="text/javascript">
var num = 1;
function f1 () {
return num;
}
console.log("f1:" + f1());
console.log("all->" +num);
</script>
- window.访问全局变量
console.log("window_num:" + window.num)
- 获取window的函数
var old_aler = window.alert;
window.alert = old_aler;
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-QXrEe6M6-1632733557327)(JavaScript.assets/image-20210926142503625.png)]
6.7、规范
为了避免太多的全局变量,我们建议自定义全局变量
const PI = 3.14
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Vo6qNAIP-1632733557328)(JavaScript.assets/image-20210926142914919.png)]
6.8、局部作用域
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ZSYzyKHE-1632733557329)(JavaScript.assets/image-20210926143633289.png)]
6.9、常量
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-nLS5wJRs-1632733557330)(JavaScript.assets/image-20210926143715957.png)]
7、对象
7.1、方法
this是无法指向的;是默认指向调用它的那个对象
- demo
var person = {
name: "sly",
birth: 2000,
age: function(){
var now = new Date().getFullYear();
return now - this.birth;
}
}
- 拆开:demo2
<script type="text/javascript">
function getAge () {
var now = new Date().getFullYear();
return now - this.birth;
}
var person = {
name: "sly",
birth: 2000,
age = getAge()
}
</script>
7.2、apply
被动调用
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-J9z1FKAQ-1632733557331)(JavaScript.assets/image-20210926145825225.png)]
8、Date函数
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-IyyDAJVb-1632733557331)(JavaScript.assets/image-20210926150655553.png)]
9、JSON
JSON一切皆为对象,任何JS支持的类型都可以用JSON来表示
- 对象
{}
- 数组
[]
- 所有键值对,都是用
key:val
- JSON(JavaScript Object Notation, JS 对象简谱) 是一种轻量级的数据交换格式。
- 采用完全独立于编程语言的文本格式来存储和表示数据。
- 简洁和清晰的层次结构使得 JSON 成为理想的数据交换语言。
- 并有效地提升网络传输效率。
9.1、JS与JSON之间的转换
JSON.stringify(obj)
JSON.parse(string)
<script type="text/javascript">
var person = {
name:"htm",
age:18,
sex:"女"
}
var j = JSON.stringify(person)
//输出结果
//'{"name":"htm","age":18,"sex":"女"}'
var o = JSON.parse('{"name":"htm","age":18,"sex":"女"}')
</script>
10、面向对象编程
10.1、什么是面向对象
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Sg002csC-1632733557332)(JavaScript.assets/image-20210926160710145.png)]
10.2、原型继承
关键字:proto
- demo
<script type="text/javascript">
function Student (name) {
this.name = name;
}
Student.prototype.hello = function(){
alert("hello!~")
}
</script>
10.3、继承
<script type="text/javascript">
class P1 {
constructor() {
this.id = "a";
}
foo() {
console.log("P1:", this.id);
}
}
class CP1 extends P1{
foo() {
super.foo();
console.log("CP1:", this.id);
}
}
var a = new CP1();
a.foo();
</script>
10.4、原型链
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-cxLmBaLC-1632733557333)(JavaScript.assets/image-20210926213825443.png)]
11、BOM对象*
1、window
浏览器窗口
window.alert("hello")
window.innerHeight
window.outerHeight
2、navigator
封装了浏览器的信息;不建议使用,因为用户可以自定义
navigator.appName
'Netscape'
navigator.appVersion
'5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Mobile Safari/537.36'
navigator.userActivation
UserActivation {hasBeenActive: true, isActive: true}hasBeenActive: trueisActive: true[[Prototype]]: UserActivation
navigator.userAgent
'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Mobile Safari/537.36'
navigator.platform
'Win32'
3、Screen
screen.width
354
screen.height
660
4、location
location
location.reload()
location.assign('https://www.baidu.com')
5、Document*
document.getElementById("logo");
document.title = 'hello wsr'
document.cookie //服务器端可以设置cookie
6、History
history.forward()
history.back()
12、DOM对象*
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ENsqq8i8-1632733557334)(JavaScript.assets/image-20210927104727023.png)]
- demo
document.getElementsByTagName('body')
var father = document.getElementById('page')[index]
father.children; father.firstChild; father.lastChild
document.getElementsByClassName('spa-index-style')
12.1、更新节点
- 插入文本 / HTML代码
var btn = document.getElementById('index-bn')
btn.innerText = '百度两下'
btn.innerHTML = '<stroger> hello <stronger/>'
- 追加操作
var father = document.getElementById('father')
var son = document.getElementById('son')
father.appendChild(son)
- 操作CSS
btn.style.fontSize = '20px'
btn.style.color = 'red' ; btn.style.background = 'green';
btn.style.margin = '100px' ;btn.style.border = '100px' ;btn.style.padding = '2em'
12.2、删除节点
var father = document.getElementById('page')
var chil = document.getElementById('index-card')
father.removeChild(chil);
//动态删除=》删除多个节点时候,children是时刻在变化的,删除节点的时候要注意!
father.removeChild(father.children[0])
12.3、插入节点
Uncaught TypeError:
将
<script type="text/javascript">
var se = document.getElementById('se')
var js = document.getElementById('js')
var ee = document.getElementById('ee')
var content = document.getElementById('content')
content.appendChild(js)
</script>
<p id="js">js</p>
<div id="content">
<p id="SE">SE</p>
<p id="EE">EE</p>
</div>
12.4、创建节点
创建一个新的标签,实现插入
Uncaught TypeError:
将
- demo1
//创建一个标签节点
var newP = document.createElement('p')
newP.id = 'newP'
newP.innerText = 'newP'
content.appendChild(newP)
//添加脚本
var myScript = document.createElement('script')
myScript.setAttribute('type','text/javascript')
content.appendChild(myScript)
//给body动态添加背景
var body = document.getElementsByTagName('body')
var style = document.createElement('style')
//<style>
style.setAttribute('type','text/css')
//<style type="text/css"></style>
style.innerHTML = 'body{background: pink;}'
body[0].appendChild(style)
//在某元素之前插入元素
var newE = document.createElement('p')
newE.id = 'newE'
newE.innerText = 'newE'
content.insertBefore(newE,newP)
13、表单操作
- HTML
<form action="" method="post">
<span>账号:</span>
<input type="text" name="user" id="user" value="" />
<span>性别:</span>
<input type="radio" name="sex" id="boy" value="boy" /> 男孩
<input type="radio" name="sex" id="girl" value="girl" checked="true"/> 女孩
</form>
- Js
var user = document.getElementById('user')
//设置文本框的值
user.value = 'hello'
//获取文本框的值
user.value
- radio的配置
var boy = document.getElementById('boy')
var girl = document.getElementById('girl')
//赋值
boy.checked = true
boy.checked ? boy.value : girl.value
//'girl'
13.1、密码加密
在form表单里,有name字段,才会被浏览器捕获?
- 方式一:
<script src="https://cdn.bootcss.com/blueimp-md5/2.10.0/js/md5.js"></script>
function chenc(){
pwd.value = md5(pwd)
return false/true; //放行与拦截
}
onclick="return check()"
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-pOlpf8nU-1632733557334)(JavaScript.assets/image-20210927143032086.png)]
- 方式二(高级):
- 新增一个隐藏域;添加name属性;专门用来传输md5;
- 取消原密码框的name属性。
- fake密码框.value = md5(in密码框.value)
- HTML
<form action="#" method="post" onclick="return check()">
<span>账号:</span>
<input type="text" name="user" id="user" value="" required/>
<br>
<span>密码:</span>
<input type="password" id="in" value="" required=""/>
<input type="hidden" id="pwd" name="pwd" value=""/>
<button type="submit" style="width:50px; height: 50px;" >超大提交</button>
</form>
- JS
<script src="https://cdn.bootcss.com/blueimp-md5/2.10.0/js/md5.js"></script>
<script type="text/javascript">
function check () {
var user = document.getElementById('user')
var in_pwd = document.getElementById('in')
var pwd = document.getElementById('pwd')
console.log(user.value)
pwd.value = md5(in_pwd.value)
console.log(pwd.value)
return false;
}
14、jQuery
JavaScript的工具库
$(selector).action()
https://jquery.cuishifeng.cn/
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>
//当所有元素加载完毕后响应时间
$(function(){}
//等价于
// $(document).ready(function(){
// })
- QuickStart
<a href="" id="test">点我</a>
- js
<script type="text/javascript">
$('#test').click(function(){
alert('hello jQuery')
})
</script>
14.1、选择器
//======原始方式==========
//获得类型
document.getElementsByTagName()
//获得id
document.getElementById()
//获得class
document.getElementsByClassName()
//======jQuery方式==========
$('p').click();
$('#id').click();
$('.class').click();
14.2、鼠标事件
- html
<style type="text/css">
#divMove{
width: 400px;
height: 400px;
border: 2px solid darkcyan;
}
</style>
mouse: <span id="mouseMove"></span>
<div id="divMove">
</div>
- JS
<script type="text/javascript">
//当所有元素加载完毕后,响应时间 等价于 $(document).ready(function(){})
$(function(){
$('#divMove').mousemove(function(e){
$('#mouseMove').text('X:' + e.pageX + 'Y:' + e.pageY)
})
})
</script>
14.3、操作DOM
- html
<ul id="test-ul">
<li class="js">js</li>
<li name="python">Python</li>
</ul>
- JS
$('.test-ul').text(); $('.test-ul').text('设置值');
$('#test-ul li[name=python]').html(); $('#test-ul li[name=python]').html('设置值')
操作CSS
$('.test-ul').text();
$('.test-ul').text('设置值');
$('#test-ul li[name=python]').html();
$('#test-ul li[name=python]').html('设置值')
$('test-ul li[name=python]').css("color","red")
隐藏和显示
$('#test-ul li[name=python]').hide()
$('#test-ul li[name=python]').show()
//反转
$('#test-ul li[name=python]').toggle()