一、常见数据类型
js常用数据类型:数字类型、字符串、布尔、数组
1.数字类型(Number) - 所有数字对应的类型
1)typeof(数据) - 获取指定数据对应的类型
console.log(typeof(20), typeof(3.1415))
2)数学对象(Math)
a.小数转整数
console.log(Math.ceil(5.8)) // 6
console.log(Math.floor(5.8)) // 5
console.log(Math.round(5.8), Math.round(5.4)) // 6 5
b.常用运算
x的y次方
console.log(Math.pow(3, 2), Math.pow(16, 0.5), Math.pow(8, 1/3)) // 9 4 2
console.log(2**3)
求绝对值
console.log(Math.abs(-19))
c.随机数
产生0~1随机小数
console.log(Math.random())
产生0~100随机整数
console.log(parseInt(Math.random()*100))
产生100~999随机数
console.log(Math.random()*899+100)
3)类型转换
Number() - 转换成数字(元数据是什么格式的数字,,就转换成什么格式的数字)
console.log(Number('12.4'))
parseFloat() - 将数据转换成带小数点的数字
parseInt() - 数数据转换成整数
Math.ceil()/ Math.floor()/Math.round()
2.字符串(String) - 容器型数据类型,不可变并且有序
1)表示: 使用’'或者"",模板字符串用``
str1 = '小明'
str2 = "四川成都"
str3 = `我是${str1},我来自${str2}`
console.log(str1, str2, str3)
console.log(typeof(str3))
2)转义字符
str4 = '\t\'abc\n123'
console.log(str4)
str5 = '\u4e00abc'
console.log(str5) // 一abc
3)获取字符
js中下标值的范围是 0 ~ 长度-1
message = 'hello world!'
console.log(message[0])
下标没有-1,越界也不会报错
console.log(message[-1], message[100]) // undefined undefined
遍历
for(let x in message){
console.log(x, message[x])
}
4)相关操作操作
a.加法
console.log('abc'+'123', 'abc'+89090, 'abc'+true) //abc123 abc89090 abctrue
不支持乘法运算
// console.log('abc'*3) // NaN
b.比较运算(和python一样)
console.log('abc'>'MN') // true
判断是否是小写字母
chr = 'p'
console.log(chr>='a' && chr<='z')
5)相关方法和属性
message = 'hello world!'
a.获取字符串长度
console.log(message.length)
c.获取字符
console.log(message.charAt(1), message.charCodeAt(1))`在这里插入代码片`
d.正则相关
字符串.match(正则表达式) - 查找字符串中能够满足正则的子串
console.log('mms234abc829llo'.match(/\d{3}/)) //['234']
console.log('mms234abc829llo'.match(/\d{3}/g)) //['234', '829']
e.字符串.replace(正则, 新子串)
message = 'abc34and8923kls0akjs98数据2规范'
console.log(message.replace(/\d+/, '*')) //abc*and8923kls0akjs98数据2规范
console.log(message.replace(/\d+/g, '*')) // abc*and*kls*akjs*数据*规范
f.切片
字符串.slice(开始下标, 结束下标)
console.log(message.slice(2,7)) // c34an
6)类型转换
String(数据) - 将数据转换成字符串
3.布尔(Boolean)
只有true和false两个值
4.数组(Array)
相当于python中的列表
1)增删改查
names = ['诸葛亮', '赵云', '曹操', '荀彧', '郭嘉', '庞统']
a.查
console.log(names[0]) // 诸葛亮
遍历
for(let index in names){
console.log(index, names[index])
}
数组.forEach(有一个或者两个参数的函数)
names.forEach(function(item,index){
console.log(`x:${item}, y:${index}`)
})
names.forEach(function(item){
console.log('item:', item)
})
b.增
数组.push(元素)
names = ['诸葛亮', '赵云', '曹操', '荀彧', '郭嘉', '庞统']
names.push('貂蝉')
console.log(names) // ["诸葛亮", "赵云", "曹操", "荀彧", "郭嘉", "庞统", "貂蝉"]
数组.splice(下标,0,元素1,元素2,元素3,…) - 在指定下标前插入指定元素
names.splice(2,0,'刘备')
console.log(names) //["诸葛亮", "赵云", "刘备", "曹操", "荀彧", "郭嘉", "庞统", "貂蝉"]
names.splice(1,0,'孙尚香', '大乔', '小乔', '甄姬')
console.log(names) // ["诸葛亮", "孙尚香", "大乔", "小乔", "甄姬", "赵云", "刘备", "曹操", "荀彧", "郭嘉", "庞统", "貂蝉"]
c.删
names = ['诸葛亮', '赵云', '曹操', '荀彧', '郭嘉', '庞统']
数组.pop()
names.pop()
console.log(names) // ["诸葛亮", "赵云", "曹操", "荀彧", "郭嘉"]
数组.splice(下标, 删除个数) - 从指定下标开始删除指定个数的元素
names = ['诸葛亮', '赵云', '曹操', '荀彧', '郭嘉', '庞统']
names.splice(2,1)
console.log(names) // ["诸葛亮", "赵云", "荀彧", "郭嘉", "庞统"]
names = ['诸葛亮', '赵云', '曹操', '荀彧', '郭嘉', '庞统']
names.splice(2,2)
console.log(names) // ["诸葛亮", "赵云", "郭嘉", "庞统"]
d.改
数组[下标] = 值
names = ['诸葛亮', '赵云', '曹操', '荀彧', '郭嘉', '庞统']
names[3] = '貂蝉'
console.log(names) // ["诸葛亮", "赵云", "曹操", "貂蝉", "郭嘉", "庞统"]
names[10] = '吕布'
console.log(names) // ["诸葛亮", "赵云", "曹操", "貂蝉", "郭嘉", "庞统", empty, empty, empty, empty, "吕布"]
names = ['诸葛亮', '赵云', '曹操', '荀彧', '郭嘉', '庞统']
// names[-1] = '董卓' // 报错
// console.log(names)
2)相关方法
a.数组.every(函数) - 检测数组中所有的元素是否满足函数返回值提供的条件
函数 - 需要一个参数,这个参数指向的是数组中的每个元素
检测scores中是否所有的元素都大于20
scores = [29, 89, 78, 67, 99, 45, 75, 39]
result = scores.every(function(item){
return item>20
})
console.log(result)
检测names中所有的名字是否都姓 张
names = ['张小明', '张三', '张三丰', '张无忌', '张翠山']
result = names.every(function(item){
return item[0]=='张'
})
console.log(result)
b.数组.filter(函数) - 获取数组所有满足函数返回值要求的元素
函数 - 需要一个参数,这个参数指向的是数组中的每个元素
scores = [29, 89, 78, 67, 99, 45, 75, 39]
result = scores.filter(function(item){
return item<60
})
console.log(result) // [29, 45, 39]
c.数组.join(分隔符=’,’) - 将数组中所有的元素适用分隔符拼接成一个字符串
names = ['张小明', '张三', '张三丰', '张无忌', '张翠山']
result = names.join()
console.log(result) // 张小明,张三,张三丰,张无忌,张翠山
result = names.join('')
console.log(result) // 张小明张三张三丰张无忌张翠山
scores = [29, 89, 78, 67, 99, 45, 75, 39]
result = scores.join()
console.log(result) // 29,89,78,67,99,45,75,39
d.数组.map(函数) - 将原数字中所有的元素按照函数做指定的操作后,产生新的数组
scores = [29, 89, 78, 67, 99, 45, 75, 39]
newScores = scores.map(function(item){
return item / 10
})
console.log(newScores) // [2.9, 8.9, 7.8, 6.7, 9.9, 4.5, 7.5, 3.9]
e.数组.reduce(函数, 初始值)
运算规则和python中的reduce一样
scores = [29, 89, 78, 67, 99, 45, 75, 39]
求所有元素的和
result = scores.reduce(function(x, item){
return x+item
}, 0)
console.log(result)
求所有元素个位数的和
result = scores.reduce(function(x, item){
return x+item%10
}, 0)
console.log(result)
f.排序
数组.sort(函数)
函数有两个参数,指向的都是序列中的元素
scores = [29, 89, 78, 67, 99, 45, 75, 39]
scores.sort(function(a, b){
// 按照元素的大小从小到大排序
// return a-b
// 按照元素的大小从大到小排序
// return b-a
// 按照元素个位数的大小从小到大排序
// return a%10 - b%10
// 按照元素各位数的和的大小从大到小排序
sumA = 0
for(let x in String(a)){
sumA += parseInt(String(a)[x])
}
sumB = 0
for(let x in String(b)){
sumB += parseInt(String(b)[x])
}
return sumB - sumA
})
console.log(scores)
二、对象
1.对象
js中的对象可以看成是python中字典和对象的结合
1)对象字面量
stu1 = {
'name': 'xiaoming',
'age': 18,
'sex': '男'
}
stu2 = {
name: '小花',
age: 20,
sex: '女'
}
console.log(stu1['name'], stu1.name)
console.log(stu2['sex'], stu2.sex)
2.构造函数(定义类) - 用来创建对象的函数,函数名就相当于类名
1)相当于定义类
function 类名(){
//添加对象属性和对象方法
this.属性 = 值
this.方法 = 函数
}
2)创建对象
对象 = new 类名()
function Student(name, age=18, sex='男'){
// 添加对象属性
this.name = name
this.age = age
this.sex = sex
this.score = 0
// 添加对象方法
this.eat = function(food){
console.log(`${this.name}在吃${food}`)
}
}
stu3 = new Student('张三')
console.log(stu3) // Student {name: "张三", age: 18, sex: "男", score: 0, eat: ƒ}
stu4 = new Student('李四', 30, '女')
console.log(stu4) // Student {name: "李四", age: 30, sex: "女", score: 0, eat: ƒ}
// 使用对象属性
console.log(stu3['name'], stu3.name)
// 调用对象方法
stu4.eat('豆腐')
stu3.eat('酸辣粉')
// 练习:创建一个dog类,有属性名字、年龄、品种、颜色、性别;方法:叫唤
function Dog(name, age=1, type='土狗', color='黄色', sex='公狗'){
this.name = name
this.age = age
this.type = type
this.color = color
this.sex = sex
this.bark = function(){
console.log(this.name+':汪汪汪!')
}
}
dog = new Dog('大黄')
dog2 = new Dog('财财',2,'土狗','黑色')
console.log(dog)
dog.bark()
3.属性的操作
1)查
对象[属性名]
对象.属性
console.log(dog['name'], dog.name) // 大黄 大黄
2)改/增
对象[属性名] = 值 - 如果没有指定属性就是添加,有就是修改
对象.属性 = 值 - 如果没有指定属性就是添加,有就是修改
dog.name = '小白'
console.log(dog['name'], dog.name) //小白 小白
dog['weight'] = 20
console.log(dog.weight, dog['weight']) // 20 20
console.log(dog)
console.log(dog2)
4.类的prototype属性
给指定类所有的对象添加属性和方法(这儿的所有的对象可以是添加前创建的,也可以是添加后创建)
类名.prototype.属性 = 值
Dog.prototype.height = 70
console.log(dog.height)
console.log(dog2.height)
String.prototype.countNum = function(){
count = 0
for(let x in this){
if(this[x] >='0' && this[x] <= '9'){
count ++
}
}
return count
}
console.log('abc'.countNum())
console.log('123ab119c10'.countNum())
Number.prototype.int = function(){
return parseInt(this)
}
console.log(12.34.int())
console.log(-3.14.int())
三、DOM操作
1.什么DOM
DOM是 doucument object model的缩写, 文档对象模型
js中自带一个document对象,指向的是当前网页的内容(包含了body以及body中所有的可见标签)
2.DOM操作 - js通过操作document对象来操作网页内容
1)获取节点(获取标签)
a.直接获取
document.getElementById(id值) - 根据id属性值获取节点(返回的是标签/节点对象)
document.getElementsByClassName() - 根据class属性值获取节点(返回值是类似数组的容器-HTMLCollection, 容器中的元素是标签对象)
document.getElementsByTagName() - 根据标签名获取节点(返回HTMLCollection对象,元素是选中的所有标签对象)
b.间接获取
获取一个标签的父节点:节点对象.parentElement
获取一个标签的子节点:节点对象.children/节点对象.firstElementChild/节点对象.lastElementChild
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<h1>1.直接获取节点</h1>
<p id="p1" class="c1">我是段落1</p>
<a href="">我是超链接1</a>
<a href="" class="c1">我是超链接2</a>
<p>我是段落2</p>
<p>我是段落3</p>
<script type="text/javascript">
// 1.获取节点
// 1)根据id获取节点
p1 = document.getElementById('p1')
console.log(p1)
// 2)根据class获取节点
c1Array = document.getElementsByClassName('c1')
console.log(c1Array)
// 注意:HTMLCollection对象遍历的时候不能使用for-in
for(let x = 0; x<c1Array.length;x++){
console.log(x, c1Array[x])
}
// 3)根据标签名获取节点
pArray = document.getElementsByTagName('p')
console.log(pArray)
</script>
<h1>2.间接获取节点</h1>
<div id="div1">
<p id="p2"><a href="">我是超链接5</a>我是段落5</p>
<a href="">我是超链接3</a>
<h4>我是4级标题1</h4>
</div>
<script type="text/javascript">
// 1.获取父节点
p2 = document.getElementById('p2')
div1 = p2.parentElement
console.log(div1)
// 2.获取子节点
div1Children = div1.children
console.log(div1Children)
firstChild = div1.firstElementChild
lastChild = div1.lastElementChild
console.log('大儿子:', firstChild)
console.log('小儿子:', lastChild)
</script>
</body>
</html>
四、节点的创建添加和删除
1.创建节点
document.createElement(标签名) - 返回节点对象(节点不会添加网页中)
2.添加节点(将节点放到网页中去)
节点对象1.appendChild(节点对象2) - 将节点对象2添加到节点对象1的最后
节点1.inserBefore(节点2,节点3) - 在节点1中节点3的前面插入节点2
3.删除节点(删除网页中指定标签)
节点.remove() - 删除指定节点
4.拷贝节点
节点.cloneNode(false) - 浅拷贝一个节点
节点.cloneNode(true) - 深拷贝一个节点
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div id="box1">
<p id="p1">我是段落1</p>
</div>
<div id="box2" style="background-color: cadetblue; width: 100px; height: 40px; margin-bottom: 10px;">
<div id="" style="background-color: red; width: 40px; height: 25px;">
</div>
</div>
<script type="text/javascript">
// 1.创建节点
a1 = document.createElement('a')
// 2.添加节点
// 在最后添加子节点
box1 = document.getElementById('box1')
box1.appendChild(a1)
// 在指定位置插入子节点
p1 = document.createElement('p')
box1.insertBefore(p1, box1.firstElementChild)
img1 = document.createElement('img')
box1.insertBefore(img1, document.getElementById('p1'))
// 3.删除节点
p1 = document.getElementById('p1')
p1.remove()
// box1.remove()
// 4.复制节点
box2 = document.getElementById('box2')
// 浅拷贝
cb1 = box2.cloneNode()
// 深拷贝
cb2 = box2.cloneNode(true)
body = document.getElementsByTagName('body')[0]
body.appendChild(cb1)
body.appendChild(cb2)
</script>
</body>
</html>
五、标签的属性
1.双标签标签内容属性
innerText - 普通文本内容
innerHTML - html内容
2.普通属性(原来标签的属性在js标签对象中都有对应的属性)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<p id="p1" >我是段落1</p>
<img src="img/anchor.png" title="" alt="" >
<button type="button" onclick="addAction()">确定</button>
<script type="text/javascript">
w = 100
h = 100
function addAction(){
img1 = document.getElementsByTagName('img')[0]
w += 10
h += 10
img1.style.width = w+'px'
console.log(img1.style.width)
img1.style.height = h+'px'
}
</script>
<script type="text/javascript">
// 1.双标签的内容
p1 = document.getElementById('p1')
// 获取标签内容
console.log(p1.innerText, p1.innerHTML) // 我是段落1 我是段落1
// 修改标签内容
// p1.innerText = 'hello world!'
// p1.innerHTML = 'hello world!'
// p1.innerText = '<a href="https://www.baidu.com">百度</a>'
p1.innerHTML = '<a href="https://www.baidu.com">百度</a>'
// 2.普通属性
img1 = document.getElementsByTagName('img')[0]
img1.src = 'img/hat1.png'
img1.title = '海贼王'
console.log(img1.src)
p1.style = 'width:200px;background-color:red;'
p1.style.fontSize = '30px'
</script>
</body>
</html>