JavaScript小结
1.数据类型
1.3对象
JavaScript中的所有键都是字符串,值是任意对象
var 对象名 = {
属性名:属性值,//键值对
属性名:属性值,
属性名:属性值,
}
var person={
name:"小明",
age: 18,
score: 100,
qq: 2452466220
}
1.对象赋值
person.name
'小明'
person.name="aa"
'aa'
person.name
'aa'
2.使用一个不存在的对象属性,不会报错
person.hah
undefined
3.通过delete动态删减对象的属性
delete person.name
true
person
{age: 18, score: 100, qq: 2452466220}
4.动态添加对象的属性:直接给新的属性赋值
person.haha="haha"
'haha'
person
{age: 18, score: 100, qq: 2452466220, haha: 'haha'}
5.判断属性值是否在这个对象中
"age" in person
true
"adress" in person
false
'toString' in person
true//继承了父类的属性
6.判断一个属性是否是这个对象自身拥有的hasOwnProperty()
person.hasOwnProperty('age')
true
person.hasOwnProperty('toString')
false
拓展:forEach和forin遍历数组
var age=[12,23,43,14,42,33]
age.forEach(function (value){
console.log(value)
}
for (var ageKey in age) {//ageKey是数组下标
console.log(age[ageKey]);
}
1.4Map和Set
2.函数
2.1定义函数
绝对值函数
定义方式一
function abs(x){
if(x>=0){
return x;
}else{
return -x;
}
}
一旦执行到return代表函数结束,返回结果
如果没有执行return,函数执行完也会返回结果(undefined)
定义方式二
var abs=function(x){
if(x>=0){
return x;
}else{
return -x;
}
}
将匿名函数赋值给abs,通过abs调用函数
参数问题
JavaScript可以传任意个参数,也可以不传递参数,并不会报错
假设不存在参数,如何规避?
var abs=function(x){
//手动抛出异常来判断
if(tyoeof x!=='number'){
throw 'Not a Number!'
}
if(x>=0){
return x;
}else{
return -x;
}
}
arguments
var abs = function(x){
console.log("x=>",+ x)
for (var i=0;i<arguments.length;i++){
console.log(arguments[i]);
}
if(x>=0){
return x;
}else{
return -x;
}
}
传递进来的所有参数,是一个数组
rest
获取除了已经定义的参数之外的所有参数
var aaa= function (a,b,...rest){
console.log("a=>",+a);
console.log("b=>",+b);
console.log(rest)
}
2.2变量的作用域
在JavaScript中,var定义的变量实际是有作用域的。
假设在函数体中声明,则在函数体外不可以使用(闭包)
function qj(){
var x=1;
x=x+1
}
x=x+2;//Uncaught ReferenceError: x is not defined
内部函数可以访问外部函数成员,反之则不行
function qj(){
var x=1;
function qj2(){
var y=x+1;//2
console.log(y);
}
qj2();
var z=y+1;//Uncaught ReferenceError: y is not defined
}
JavaScript中函数查找变量从自身函数开始由内向外查找
function qj(){
var x=1;
function qj2(){
var x='A'
console.log('inner'+x);//A
}
qj2()
console.log('outer'+x);//1
}
假设外部存在这个同名的函数变量,则内部函数会屏蔽外部函数的变量
全局函数
全局对象window
var x='xxx';
window.alert(x);
alert(window.x)
默认所有的全局变量,都会自动绑定在window对象下。
alert()函数本身也是一个window变量;
规范
由于所有的全局变量都会绑定到我们的window上,如果不同的js文件使用了相同的全局变量,就会产生冲突。
解决方法:将代码放入自己定义的唯一空间名字中,降低全局命名冲突
//唯一全局变量
var Legends={};
//定义全局变量
Legends.name='Riven';
Legends.add = function (a,b){
return a+b;
}
局部作用域let
ES6 let关键字,解决局部作用域冲突问题
function aaa(){
for (var i = 0; i < 100; i++) {
console.log(i)
}
console.log(i+1)//101
}
function bbb(){
for (let i = 0; i < 100; i++) {
console.log(i)
}
console.log(i+1)//Uncaught ReferenceError: i is not defined
}
常量const
ES6之前,常量:全部用大写字母命名
ES6引入了常量关键字const
2.3方法
定义方法
方法就是把函数放在对象的里面。对象只有两个东西:属性和方法
var goddess={
name:'Riven',
birth:2012,
age:function (){
var now =new Date().getFullYear();//获取当前年份Date().getFullYear()
return now-this.birth;
}
}
//属性
goddess.name
//方法,一定要带括号
goddess.age()
apply
this是无法指向的,是默认指向调用它的那个对象,在JavaScript中,apply可以控制this指向
function getAge(){
var now =new Date().getFullYear();
return now-this.birth;
}
var goddess={
name:'Riven',
birth:2012,
age: getAge//函数名
};
console.log(getAge.apply(goddess,[])/*指向goddess,参数为空*/)
3.内部对象
3.1 Date
基本使用
var now = new Date();//Mon Nov 22 2021 21:20:40 GMT+0800 (中国标准时间)
now.getFullYear();//年
now.getMonth();//月 0~11
now.getDate();//日
now.getDay();//周几
now.getHours();//时
now.getMinutes();//分
now.getSeconds();//秒
now.getTime();//时间戳 全世界统一 1979.1.1 0:00:00到现在的毫秒数
console.log(new Date(1637587902736))//VM376:1 Mon Nov 22 2021 21:31:42 GMT+0800 (中国标准时间) 时间戳转换为时间
now.toLocaleString()//2021/11/23 下午7:26:40
3.2 JSON
json是什么?
- JSON(JavaScript Object Notation, JS 对象简谱) 是一种轻量级的数据交换格式。
- 简洁和清晰的层次结构使得 JSON 成为理想的数据交换语言。
- 易于人阅读和编写,同时也易于机器解析和生成,并有效地提升网络传输效率。
在JavaScript中一切结尾对象、任何js支持的类性都可以用JSON来表示:
格式:
- 对象都用{}
- 数组都用[]
- 所有的键值对都使用 key:value
JSON字符串和JS对象的转化
var user={
name:'Riven',
age:20,
sex:'女'
}
//对象转换为JSON字符串
var jsonUser= JSON.stringify(user)
//JSON字符串转换为对象 参数为JSON字符串
var user2= JSON.parse(jsonUser)
4.面向对象编程
ES6之前
function Student(name){
this.name=name
}
//给student新增一个方法
Student.prototype.hello=function (){
alert('hello')
}
var student= new Student('xiaoming')
class继承
class关键字是在ES6引入的
1.定义一个类,属性,方法
class Student{
constructor(name) {
this.name=name;
}
hello(){
alert('hello')
}
}
var student= new Student('xiaoming')
2.继承
var student=new Student('xiaohong');
class xiaoStudent extends Student{
constructor(name,grade) {
super(name);
this.grade=grade;
}
myGrade(){
alert('我是一名小学生')
}
}
var zhangsan=new xiaoStudent('zhangsan',1)
5.操作BOM对象(重点)
浏览器介绍
JavaScript和浏览器关系?
JavaScript诞生就是为了能够让他在浏览器中运行!
BOM:浏览器对象模型
window
window代表浏览器窗口
window.innerWidth
1849
window.innerHeight
518
window.outerWidth
1403
window.outerWidth
804
window.outerHeight
1047
//浏览器窗口宽高
window.alert('wonendie')
undefined
Navigator
Navigator,封装了浏览器的信息
navigator.platform
'Win32'
navigator.appVersion
'5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.45 Safari/537.36 Edg/96.0.1054.29'
navigator.appName
'Netscape'
大多数时候,我们不会使用navigator对象,因为会被人为修改,不建议使用这些属性来判断和编写代码
screen
代表屏幕尺寸
screen.width
1920 px
screen.height
1080 px
location
location代表当前页面的URL信息
host: "www.baidu.com"
href: "https://www.baidu.com/"
protocol: "https:"
reload: ƒ reload()//刷新网页
//设置新的地址
location.assign('https://www.cnblogs.com/rfcaTheshy/')
document
document代表当前的页面,HTML DOM文档树
获取具体的文档树节点
<dl id="app">
<dd>Java</dd>
<dd>JavaSE</dd>
<dd>JavaEE</dd>
</dl>
<script>
var dl=document.getElementById('app');
</script>
获取cookie
document.cookie
history
代表浏览器的历史记录
history.back()//后退
history.forward()//前进
6.操作DOM对象(重点)
DOM:文档对象模型
核心
浏览器网页就是一个Dom树形结构
- 更新:更新DOM节点
- 遍历DOM节点:得到DOM节点
- 删除:删除一个DOM节点
- 添加:添加一个新的节点
要操作一个DOM节点,就必须先获得这个DOM节点
//对应css选择器
var h1=document.getElementsByTagName('h1');//返回的是一个数组
var p1=document.getElementById('p1');
var p2=document.getElementsByClassName('p2');
var father = document.getElementById('father');
var childrens = father.children;//获取父节点下的所有子节点
更新节点
操作文本
- id1.innerText='456'修改文本的值
- id1.innerHTML='<strong>456</strong>';可以解析HTML文本标签
操作css
id1.style.color='blue';
id1.style.fontSize='5em';
删除节点
步骤:先获取父节点,再通过父节点删除自己
<body>
<div id="father">
<h1>标题一</h1>
<p id="p1">p1</p>
<p class="p2">p2</p>
</div>
<script>
var self=document.getElementById('p1');
var father=p1.parentElment;
father.removeChild(p1);//要有id
//删除是一个动态的过程,删除完children[0]后,children[1]变为children[0]
father.removeChild(father.children[0])
</script>
插入节点
我们获得了某个DOM节点,假设这个DOM节点是空的,我们通过innerHTML就可以增加一个元素了,如果这个DOM节点已经存在元素了,则这些元素会被覆盖
追加
<p id="js">JavaScript</p>
<div id="list">
<p id="SE">JavaSE</p>
<p id="EE">JavaEE</p>
<p id="ME">JavaME</p>
</div>
<script>
var js=document.getElementById('js');
var list=document.getElementById('list');
list.appendChild(js);//追加到后面
</script>
创建一个新的标签实现插入
var newP=document.createElement('p')//创建一个P标签
newP.id='newP';
newP.innerText='hello world';
list.appendChild(newP);
//创建一个style标签修改背景颜色
var myStyle=document.createElement('style');
myStyle.setAttribute('type','text/css')
myStyle.innerHTML='body{background-color:red}';
var head=document.getElementsByTagName('head');
head[0].appendChild(myStyle);
//修改背景颜色
var body=document.getElementsByTagName('body')//此处获取的是一个数组,要用body[0]去选择
body[0].style.backgroundColor='yellow';
insert
var EE=document.getElementById('EE');
var JS=document.getElementById('js');
var list=document.getElementById('list');
//要包含的节点.insertBefore(newNode,targetNode)
list.insertBefore(JS,EE);
7.操作表单(验证)
表单是什么 form DOM树
- 文本框 text
- 下拉框 < select>
- 单选框 radio
- 多选框 checkbox
- 隐藏域 hidden
- 密码框 password
- ......
表单的目的:提交信息
获得要提交的信息
<form action="#" method="post">
<span>用户名:</span><input type="text" id="username"><br/>
<span>密   码:</span><input type="password" id="password"><br/>
<!-- 多选框的值,就是定义好的value -->
<span>性   别:</span>
<input type="radio" name="sex" value="man" id="boy">男
<input type="radio" name="sex" value="woman" id="girl">女
</form>
<script>
var input_text=document.getElementById('username');
var input_password=document.getElementById('password');
//得到输入框的值
input_text.value;
//修改输入框的值
input_text.value='123123';
var boy_radio=document.getElementById('boy');
var girl_radio=document.getElementById('girl');
//对于单/多选框等固定的值,boy_radio只能取到当前的值
//boy_radio.checked;产看返回的结果是否为true(被选中时)
girl_radio.checked='true';//赋值
8.jQuery
jQuery库,里面存在大量的JavaScript函数
获取jQuery库
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="lib/jquery-3.6.0.js"></script>
</head>
<body>
<!--
公式:$(selector).action()
-->
<a href="" id="text-jQuery">点我</a>
<script>
//选择器就是css选择器
$('#text-jQuery').click(function (){
alert('hello,jQuery');
})
</script>
</body>
</html>
选择器
<script>
//原生js,选择器少,麻烦不好记
//id
document.getElementById();
//标签
document.getElementsByTagName();
//类
document.getElementsByClassName();
//jQuery
$('p')//标签选择器(p标签)
$('#id')//id选择器
$('.class')//类选择器
</script>
事件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="lib/jquery-3.6.0.js"></script>
<style>
#divMove{
border: 3px solid black;
width: 500px;
height: 500px;
}
</style>
</head>
<body>
<!--获取鼠标当前的一个坐标-->
mouse: <span id="mouseMove"></span>
<div id="divMove">
在这里移动鼠标试试
</div>
<script>
/*当网页加载完毕后,响应事件
$(document).ready(function(){
})
简化后
$((function(){
}));
*/
$((function (){
$('#divMove').mousemove(function (e){
$('#mouseMove').text('x:'+e.pageX+' y:'+e.pageY);
})
}))
</script>
</body>
</html>
操作DOM元素
节点操作文本
$('#text-ul li[name=python]').text();//获得值
$('#text-ul li[name=python]').text('123123');//获得值
$('#text-ul li[name=python]').html();//获得值
$('#text-ul li[name=python]').html('<h1>666</h1>');//获得值
css的操作
$('.js').css({'color':'red','background':'yellow'})
元素的显示和隐藏(本质:display:none)
$('.js').hide();//隐藏
$('.js').show();//显示
小技巧
- 巩固JS:看jQuery源码,看游戏源码
- 巩固HTML,css:扒网站,全部down下来,然后对应修改看效果

浙公网安备 33010602011771号