1、输入输出语句
<script>
// 1、向文档输出内容
// 1.1输出普通字符串
document.write('hello world')
// 1.2输出HTML标签
document.write('<h1>hello</h1>')
// 2、页面弹出框
alert('弹出警示框')
// 3、控制台输出内容,供调试程序使用
console.log('调试程序')
// 4、输入内容,也是弹出框让用户输入
prompt('请输入内容')
</script>
2、变量
建议使用let ,不要使用var(已过时)
// 先声明再赋值
let a
a= 1
// 声明并同时赋值
let b=10
不允许重复声明某个变量
let name='11'
let name='22' //这是不允许的
但是可以同时声明多个变量
let name='11',a=1
案例—输入姓名并输出到页面
let name = prompt('输入姓名:') // 将输入的内容用变量保存下来
document.write(name)
3、常量
使用 const 修饰
- 申明的同时需要赋值
- 不允许重新赋值
const a
a=10 // 这是错误的
const a=10
a=11 // 这也是错误的
const a=10 // 这才是正确的
4、模板字符串
- 使用 反引号 `` 包裹(在tab键上方)
- 内容拼接变量时,用 ${}包裹变量
let name='张三'
let age=18
document.write(`我叫${name},今年${age}岁`)
5、null 和 undefined
- null 表示给变量赋值了,但是内容为空
- undefined 表示声明了变量,但是未赋值
let x
console.log(x) // undefined
let x = null
console.log(x) // null
也可以给变量赋值undefined
二者计算时有区别
let x = null
console.log(x+1) // 1 空+1=1
let y = undefined
console.log(y+1) // NaN 未定义+1=非数
6、数据类型及类型检测
let num = 1
console.log(typeof num) // number
let str = 'hello'
console.log(typeof str) // string
let b = true
console.log(typeof b) // boolean
let d = undefined
console.log(typeof d) // undefined
let n = null
console.log(typeof n) // object
将string转为number类型
let str = '11'
// 方法1 使用 Number
let num = Number(str) // 推荐使用这个
console.log(typeof num)
// 方法2 使用 +
let num2 = +str
console.log(num2,typeof num2)
7、数组及其方法
(1)数组的声明方式
// 常用方式
let arr = [1,2,'hello',null] // 弱类型语言,数组中可以存储不同数据类型的元素
console.log(arr)
// 使用对象方式创建
let arr1 = new Array(1,2,3,'a')
console.log(arr1)
(2)添加数据
- 向数组末尾添加一个或多个元素
使用函数push,返回值是数组的新长度
let arr = [1,2,3]
arr.push(4)
console.log(arr)
[1,2,3,4]
let arr = [1,2,3]
let len = arr.push(4,5)
console.log(arr,len)
[1, 2, 3, 4, 5] 5
- 向数组头部添加一个或多个元素
使用函数 unshift,返回值是数组新长度
let arr = [1,2,3]
arr.unshift(0)
console.log(arr)
[0,1,2,3]
let arr = [1,2,3]
let len = arr.unshift(4,5)
console.log(arr,len)
[4, 5, 1, 2, 3] 5 // 注意是 4,5
(3)删除元素
- 删除数组末尾一个元素
let arr = [1,2,3,4,5]
arr.pop()
console.log(arr)
[1,2,3,4]
- 删除数组头部第一个元素
let arr = [1,2,3,4,5]
arr.shift()
console.log(arr)
[2,3,4,5]
- 删除若干个元素
arr.splice(操作的下标,删除的个数)
删除的个数是可选的,如果不指定,就从指定下标开始删除直到数组末尾
let arr = [1,2,3,4,5]
arr.splice(2,2) // 从下标2开始删除2个元素
console.log(arr)
[1, 2, 5]
8、对象
- 增删改查
let student = {
name: '张三',
age: 20,
}
// 增加属性
student.sex = '男'
// 修改属性
student.age = 21
// 查询
console.log(student.name, student.age, student.sex)
// 删除属性
delete student.age
console.log(student)
- 另一种写法
对象的属性名也用 引号包裹,获得属性值时,就需要使用 对象名[‘属性名’] 这种方式
let obj = {
'name':'js'
}
console.log(obj['name'])
- 对象的方法
document.write() 就是document对象的方法write
let teacher = {
name: 'pink',
sum: function(x=1, y=0) { // 默认值
console.log(x + y)
}
}
teacher.sum()
teacher.sum(10,20)
- 遍历对象
let student = {
name: '张三',
age: 20,
sex: '男'
}
// 对象遍历
for(let key in student) {
console.log(key) // 输出的是属性名 key === 'name' 'age' 'sex'
// 因为 key 是字符串类型,所以不能使用 student.key 来获取属性值
console.log(student[key])
}
9、随机数
Math.random() 函数生成 一个 [0,1) 的数字,是小数
let num = Math.random()
console.log(num)
如果需要得到整数,使用Math.floor() 向下取整
let num = Math.floor(Math.random()*11)
console.log(num) // 可以得到 0-10 的整数
生成 n至m 的随机数
Math.floor(Math.random()*(m-n+1))+n
function getRandomNum(n, m) {
let num = Math.floor(Math.random()*(m-n+1)+n)
return num
}
console.log(getRandomNum(5,10))
10、DOM对象
浏览器根据HTML标签生成的js对象,所有的标签属性都可以在这个对象上找到,修改这个对象的属性会自动映射到标签身上。
DOM的核心思想是把网页内容当做对象来处理
document对象是DOM提供的一个对象,他提供的属性和方法都是用来访问和操作网页内容的,如document.write() 方法。
(1)根据css选择器来获取DOM元素
会选择匹配的第一个元素
document.querySelector('css选择器')
参数包含 一个或多个 有效的css选择器,用引号包裹
返回值是一个对象
<body>
<div class='first'>123</div>
<div class='second'>abc</div>
<p id='p1'>hello</p>
<ul>
<li>111</li>
<li>222</li>
<li>333</li>
</ul>
<script>
// 1. 选择标签名,会选中第一个该标签
const div1 = document.querySelector("div")
// 2. 选择类名
const div2 = document.querySelector('.second')
console.log(div1)
// 3. 选择id
const p = document.querySelector('#p1')
console.log(p)
// 4. 获取 ul 中的第一个 li
const li = document.querySelector('ul li:first-child')
console.log(li)
</script>
</body>
(2)操作元素内容
1、元素的innerText属性
可以将纯文本内容添加或更新到任意标签的位置,但是不能解析标签
<body>
<div class='box'>我是一个标签</div>
<script>
let box = document.querySelector('.box')
console.log(box.innerText)
// 修改标签包裹的内容
box.innerText = '我是一个盒子'
</script>
</body>
2、元素的innerHTML属性
修改标签包裹的内容,并可以解析标签
<body>
<div class='box'>我是一个标签</div>
<script>
let box = document.querySelector('.box')
console.log(box.innerText)
// 修改标签包裹的内容,并可以解析标签
box.innerHTML = '<strong>我是一个盒子</strong>'
</script>
</body>
(3)修改元素的属性
先获取标签对象,通过 对象名.属性名 = 属性值 来修改
<body>
<img src='./images/1.avif' alt=''/>
<script>
function getRandomNum(m,n){
return Math.floor(Math.random()*(n-m+1)+m)
}
const img = document.querySelector('img')
// 随机展示图片
let num = getRandomNum(1,4)
img.src = `./images/${num}.avif`
</script>
</body>
(3)修改元素的样式
1、通过 .style 进行修改
对象名.style.属性名 = 属性值
属性值需要用引号括起,有些需要带上单位,如果属性名有多个单词,采用驼峰命名法
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<style>
.box{
width: 300px;
height: 600px;
background-color: red;
}
</style>
<body>
<div class='box'>111</div>
<script>
const box = document.querySelector('.box')
box.style.height = '400px'
// background-color 因为js中命名不允许有中划线,所以改成驼峰命名
box.style.backgroundColor = "green"
</script>
</body>
</html>
2、通过类名className修改样式
通过 .className = 新类名 修改
可以同时修改多个样式
<style>
.box1{
width: 300px;
height: 600px;
background-color: red;
}
.box2{
width: 300px;
height: 400px;
background-color: green;
}
</style>
<body>
<div class='box1'>111</div>
<script>
const box = document.querySelector('.box1')
box.className = 'box2'
</script>
</body>
3、通过classList添加或删除类名
使用className时,如果添加多个类,就会覆盖前面的,可以使用classList解决这一问题
<style>
.box{
width: 300px;
height: 400px;
}
.box1{
background-color: red;
}
.box2{
background-color: green;
}
</style>
<body>
<div class='box'>111</div>
<script>
const box = document.querySelector('.box')
// 追加类名
box.classList.add('box1')
// 删除类名
box.classList.remove('box1')
// 切换类名 有就删除,没有就加上
box.classList.toggle('box2')
</script>
</body>
(4)获取并设置表单元素的值和属性
<body>
<input class='input' type='text' value="hello"/>
<input type="checkbox"/>
<button class='btn'>点击</button>
<script>
// 设置input的value属性
const input = document.querySelector('.input')
input.value = '你好'
// 设置复选框 checked属性 checked默认为false,代表未选中
const ipt = document.querySelector('input')
console.log(ipt.checked)
ipt.checked = true
// 设置按钮的 disabled属性,默认为false,代表可用
const btn = document.querySelector('.btn')
console.log(btn.disabled)
btn.disabled = true // 设为禁用
</script>
</body>
(5)自定义属性
标准属性是指标签自带的属性,如 class、id等,自定义属性是HTML5新特性。
在标签上一律以 data- 开头,后接属性名
在DOM对象上一律以dataset对象方式获取
<body>
<div data-sm='small'>111</div>
<script>
const small = document.querySelector('div')
console.log(small.dataset.sm) // 输出 small
</script>
</body>
11、定时器-间歇函数
能够使用定时器函数重复执行代码,定时器函数可以开启和关闭定时器。
setInterval(函数,间隔时间)
每隔一段时间调用这个函数
间隔时间单位是 毫秒
<script>
// 写法一,里面写匿名函数
setInterval(function(){
console.log('执行一次')
},1000)
// 写法二
function fun(){
console.log('111')
}
setInterval(fun,1000) // 直接写函数名,不要带小括号
setInterval('fun()',2000) // 如果要带(),就用引号括起
</script>
setInterval() 函数返回值是该定时器的id,是唯一的,可以使用clearInterval()函数关闭定时器,里面的参数就是定时器的id
let n = setInterval('fun()',2000) // 如果要带(),就用引号括起
clearInterval(n)
案例—制作一个 同意协议的定时器
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div>
<textarea rows=10 cols=16>请阅读协议,然后同意</textarea><br>
<button class='btn' disabled>请阅读协议(5s)</button>
</div>
<script>
const btn = document.querySelector('.btn')
let time = 5
let n = setInterval(function(){
// 时间自减
time--
btn.innerHTML = `请阅读协议(${time}s)`
if(time === 0){
// 关闭定时器
clearInterval(n)
// 修改文本域内容
btn.innerHTML = '同意'
// 按钮改为可用状态
btn.disabled = false
}
},1000)
</script>
</body>
</html>
12、事件监听
元素对象.addEventListener('事件类型',要执行的函数)
事件监听三要素
- 事件源 需要获取dom元素
- 事件类型 用什么方式触发,比如鼠标点击click,鼠标经过mouseover
- 事件调用的函数 要做什么事情
<body>
<button>点击提示</button>
<script>
const btn = document.querySelector('button')
btn.addEventListener('click',function(){
alert('提示')
})
</script>
</body>
事件类型
(1)鼠标事件
- click 鼠标点击
<body>
<button>点击提示</button>
<script>
const btn = document.querySelector('button')
btn.addEventListener('click',function(){
alert('提示')
})
</script>
</body>
- mouseenter 鼠标移入
<body>
<button>提示</button>
<script>
const btn = document.querySelector('button')
btn.addEventListener('mouseover',function(){
alert('提示')
})
</script>
</body>
- mouseleave 鼠标离开
<body>
<button>提示</button>
<script>
const btn = document.querySelector('button')
btn.addEventListener('mouseleave',function(){
alert('提示')
})
</script>
</body>
(2)焦点事件
- focus 表单获得焦点
- blur 表单失去焦点
制作一个动态搜索框
![](C:\Users\zzps\Pictures\Saved Pictures\其他\Snipaste_2023-03-22_23-15-32.png)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
ul {
list-style: none;
}
.mi {
position: relative;
width: 223px;
margin: 100px auto;
}
.mi input {
width: 223px;
height: 48px;
padding: 0 10px;
font-size: 14px;
line-height: 48px;
border: 1px solid #e0e0e0;
outline: none;
}
.mi .search {
border: 1px solid #ff6700;
}
.result-list {
position: absolute;
left: 0;
top: 48px;
width: 223px;
border: 1px solid #ff6700;
border-top: 0;
background: #fff;
display: none;
}
.result-list a {
display: block;
padding: 6px 15px;
font-size: 12px;
color: #424242;
text-decoration: none;
}
.result-list a:hover {
background-color: #eee;
}
</style>
</head>
<body>
<div class="mi">
<input type="search" placeholder="小米笔记本">
<ul class="result-list">
<li><a href="#">全部商品</a></li>
<li><a href="#">小米11</a></li>
<li><a href="#">小米10S</a></li>
<li><a href="#">小米笔记本</a></li>
<li><a href="#">小米手机</a></li>
<li><a href="#">黑鲨4</a></li>
<li><a href="#">空调</a></li>
</ul>
</div>
<script>
const input = document.querySelector('[type=search]')
const ul = document.querySelector('.result-list')
input.addEventListener('focus', function(){
ul.style.display = 'block' // 显示ul列表
input.classList.add('search')
})
input.addEventListener('blur', function(){
ul.style.display = 'none' // 隐藏ul
input.classList.remove('search')
})
</script>
</body>
</html>
(3)键盘事件
- keydown 键盘按下触发
- keyup 键盘抬起触发
(4)文本事件
input 用户输入事件
制作一个发布评论的输入框
![](C:\Users\zzps\Pictures\Saved Pictures\其他\Snipaste_2023-03-22_23-28-03.png)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>评论回车发布</title>
<style>
.wrapper {
min-width: 400px;
max-width: 800px;
display: flex;
justify-content: flex-end;
}
.avatar {
width: 48px;
height: 48px;
border-radius: 50%;
overflow: hidden;
/*background: url(./images/avatar.jpg) no-repeat center / cover;*/
margin-right: 20px;
}
.wrapper textarea {
outline: none;
border-color: transparent;
resize: none;
background: #f5f5f5;
border-radius: 4px;
flex: 1;
padding: 10px;
transition: all 0.5s;
height: 30px;
}
.wrapper textarea:focus {
border-color: #e4e4e4;
background: #fff;
height: 50px; /* 输入框获得焦点后,让其高度变大 */
}
.wrapper button {
background: #00aeec;
color: #fff;
border: none;
border-radius: 4px;
margin-left: 10px;
width: 70px;
cursor: pointer;
}
.wrapper .total {
margin-right: 80px;
color: #999;
margin-top: 5px;
opacity: 0; /* 透明度为0,则不显示 */
transition: all 0.5s; /* 动画效果 */
}
.list {
min-width: 400px;
max-width: 800px;
display: flex;
}
.list .item {
width: 100%;
display: flex;
}
.list .item .info {
flex: 1;
border-bottom: 1px dashed #e4e4e4;
padding-bottom: 10px;
}
.list .item p {
margin: 0;
}
.list .item .name {
color: #FB7299;
font-size: 14px;
font-weight: bold;
}
.list .item .text {
color: #333;
padding: 10px 0;
}
.list .item .time {
color: #999;
font-size: 12px;
}
</style>
</head>
<body>
<div class="wrapper">
<i class="avatar"></i>
<textarea id="tx" placeholder="发一条友善的评论" rows="2" maxlength="200"></textarea>
<button>发布</button>
</div>
<div class="wrapper">
<span class="total">0/200字</span>
</div>
<div class="list">
<div class="item" style="display: none;">
<i class="avatar"></i>
<div class="info">
<p class="name">清风徐来</p>
<p class="text">大家都辛苦啦,感谢各位大大的努力,能圆满完成真是太好了[笑哭][支持]</p>
<p class="time">2022-10-10 20:29:21</p>
</div>
</div>
</div>
<script>
const tx = document.querySelector('#tx')
const total = document.querySelector('.total')
const item = document.querySelector('.item')
const text = document.querySelector('.text')
// 1. 当我们文本域获得了焦点,就让 total 显示出来
tx.addEventListener('focus', function () {
total.style.opacity = 1 // 透明度改为1,即显示出来
})
// 2. 当我们文本域失去了焦点,就让 total 隐藏出来
tx.addEventListener('blur', function () {
total.style.opacity = 0
})
// 3. 检测用户输入
tx.addEventListener('input', function () {
// console.log(tx.value.length) 得到输入的长度
total.innerHTML = `${tx.value.length}/200字`
})
// 4. 按下回车发布评论
tx.addEventListener('keyup', function (e) {
// 只有按下的是回车键,才会触发
// console.log(e.key)
if (e.key === 'Enter') {
// 如果用户输入的不为空就显示和打印
if (tx.value.trim()) {
// console.log(11)
item.style.display = 'block'
// console.log(tx.value) // 用户输入的内容
text.innerHTML = tx.value
}
// 等我们按下回车,结束,清空文本域
tx.value = ''
// 按下回车之后,就要把 字符统计 复原
total.innerHTML = '0/200字'
}
})
</script>
</body>
</html>
13、事件对象
事件对象里面有事件触发时的相关信息。可以判断用户按下了哪个键,鼠标点击了哪个元素等。
回调函数里面的参数e就是该事件对象。
<body>
<input />
<script>
const input = document.querySelector('input')
input.addEventListener('keyup',function(e){
console.log(e)
})
</script>
</body>
事件对象的部分常用属性有:
- type 获取当前的事件类型
- clientX / clientY 获取光标相对于浏览器可见窗口左上角的位置
- offsetX / offsetY 获取光标相对于当前dom元素的左上角的位置
- key 获取用户按下的键盘键的值
<body>
<input />
<script>
const input = document.querySelector('input')
input.addEventListener('keyup',function(e){
if(e.key === 'Enter')
console.log('按下了回车键')
})
</script>
</body>
14、定时器-延迟函数
用来让代码延迟执行的函数,只执行一次。
setTimeout(回调函数,等待的毫秒数)
<body>
<p></p>
<script>
const p = document.querySelector('p')
setTimeout(function(){
p.innerHTML = '时间到了'
}, 2000)
</script>
</body>
清除延迟函数
clearTimeout
案例:设置div 3秒后自动关闭
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
div{
width: 200px;
height: 200px;
position: absolute;
left: 0;
bottom: 0;
background-color: red;
}
</style>
</head>
<body>
<div></div>
<script>
const div = document.querySelector('div')
setTimeout(function(){
div.style.display = 'none' // 设置为 none
}, 3000)
</script>
</body>
</html>
15、Window 对象
location的数据类型是对象,它拆分并保存了URL的各个组成部分。
常用属性和方法:
- href属性获取完整的URL地址,对其赋值时用于地址的跳转
location.href = 'https://www.baidu.com'
案例:支付成功时的自动跳转
<body>
<a href="https://www.baidu.com">支付成功,<span>5</span>秒后自动跳转</a>
<script>
const span = document.querySelector('span')
let num = 5
let timerId = setInterval(function(){
num--
if(num === 0){
clearInterval(timerId)
location.href = 'https://www.baidu.com'
}
span.innerHTML = `${num}`
},1000) // 停留1s(即第5秒)
</script>
</body>
- search 属性获取地址中的携带的参数,即符号 ? 后面的部分
<body>
<form action="">
<input type='text' name='username'>
<input type='password' name='password'>
<button>提交</button>
</form>
<script>
console.log(location.search)
</script>
</body>
/JavaScript基础/事件对象.html?username=zs&password=123456
?username=zs&password=123456
- hash 属性获取地址中的哈希值,即符号 # 后面的部分
- reload 刷新页面的方法
传入参数true表示强制刷新
16、本地存储
localStorage ,只能存储字符串类型,如果传入其他类型的值,会自动转为字符串
存储数据
localStorage.setItem(key, value) // 键值对的形式, 需要使用引号包裹
获取数据
localStorage.getItem(key) // 通过键获取数据
删除数据
localStorage.removeItem(key)
存储复杂数据类型
因为只能存储字符串,当需要存储一个对象时,需要使用stringify转化为字符串,后续需要获取到这个对象时,需要使用parse把getItem得到的字符串转化。
<script>
const obj = {
name: 'zhangsan',
age: 20
}
localStorage.setItem('obj',JSON.stringify(obj))
console.log(JSON.parse(localStorage.getItem('obj')))
</script>
17、正则表达式
JavaScript中定义正则表达式的语法有两种
(1)/表达式/
const 变量名 = /表达式/
// 判断是否有符合规则的字符串,返回布尔类型
regObj.test(被检测的字符串)
<script>
const str = '我在学习javasc'
const fun = /学习/
const flag = fun.test(str)
console.log(flag)
</script>
(2)元字符
- 边界符
边界符(位置符)用来提示字符所处的位置,主要有两个字符
边界符 | 说明 |
^ | 表示匹配行首的文本(以谁开始) |
$ | 表示匹配行尾的文本(以谁结束) |
当二者在一起使用,表示必须是精确匹配
console.log(/^哈/.test('哈')) // true
console.log(/^哈/.test('哈哈')) // true
console.log(/^哈/.test('二哈')) // false
console.log(/哈$/.test('哈')) // true
console.log(/^哈$/.test('哈')) // true 以 哈 开头,以 哈 结尾, 哈哈 不符合
console.log(/^哈$/.test('哈哈')) // false
console.log(/^哈$/.test('二哈')) // false
- 量词
用来设定某个模式出现的次数
量词 | 说明 |
* | 重复0次或更多次 |
+ | 重复一次或更多次 |
? | 重复0次或1次 |
{n} | 重复 n 次 |
{n,} | 重复 n 次或更多次 |
{n,m} | 重复 n 到 m 次 |
- 字符类
[] 里面加上 - 连接符,表示一个范围
[a-z] 表示a到z 26个英文字母
[a-zA-Z] 表示大小写英文字母
[0-9] 表示0-9的数字
[] 里面加上 ^ 取反符号
[^a-z] 表示匹配除了小写字母外的字符
- 预定义类
指的是某些常见的模式的简写
预定类 | 说明 |
\d | 等价于 [0-9] |
\D | [^0-9] |
\w | [A-Za-z0-9] |
\W | [^A-Za-z0-9] |
\s | 匹配空格,包括换行符、制表符、空格,相当于[\t\r\n\v\f] |
\S | 匹配非空格 |
- 修饰符
修饰符约束正则执行的某些细节行为,如是否区分大小写,是否支持多行匹配等
/表达式/修饰符
i 正则匹配时字母不区分大小写
g 匹配所有满足正则表达式的结果,因为默认只匹配第一个
18、剩余参数
借助 … 获取剩余实参,是一个数组,置于最末函数形参之前,用于获取多余的实参。
function getSum(...arr){
console.log(arr) // [1,2,3,4]
let sum = 0
for(let i=0; i<arr.length; i++){
sum += arr[i]
}
return sum
}
console.log(getSum(1,2,3,4))
function getSum(a,b,...arr){
console.log(arr) // [3,4]
let sum = 0
for(let i=0; i<arr.length; i++){
sum += arr[i]
}
return sum
}
console.log(getSum(1,2,3,4))
19、箭头函数
// 以前的写法
const fun1 = function(){
console.log(123)
}
// 省略function,使用 =>
const fun2 = () =>{
console.log(456)
}
// 有参数
const fun3 = (x,y) =>{
console.log(x+y)
}
// 只有一个参数
const fun4 = x =>{
console.log(x)
}
// 只有一行代码,省略大括号
const fun5 = x => console.log(x)
20、数组方法
(1)map方法
map可以遍历数组处理数据,并且返回新的数组。
<script>
const arr = ['red','green','blue','yellow']
const newArr = arr.map(function(ele, index){
// ele 是元素, index是下标
console.log(index+' '+ele)
return ele + '颜色'
})
console.log(newArr)
</script>
['red颜色', 'green颜色', 'blue颜色', 'yellow颜色']
(2)join方法
join() 方法用于把数组中的所有元素转换成一个字符串,可以指定分隔符,返回一个新的数组
const newArr1 = arr.join('') // 连接成字符串
console.log(newArr1)
const newArr2 = arr.join('|') // 以|为分隔符连接
console.log(newArr2)
redgreenblueyellow
red|green|blue|yellow
(3)forEach方法
用来遍历数组元素,没有返回值
arr.forEach(function(当前数组元素,当前元素索引号){
})
const array = [1,2,3,4,5]
array.forEach(function(item,index){
console.log('当前元素是'+item, '下标是'+index)
})
箭头函数写法
let sum = 0
array.forEach(item => {
sum += item
})
console.log(sum)
(4)filter方法
过滤掉不符合条件的元素
const a = [1,2,3,4,14,354,655]
// 过滤掉小于10的数,而大于10的数将作为新数组的元素
const newa = a.filter(item => item > 10)
// 过滤掉长度小于4的单词
const b = ['hello','world','java','python']
const newb = b.filter(item => item.length > 4)
(5)reduce方法
arr.reduce(function(上一次的值,当前值){},初始值)
const arr = [1,2,3]
// 没有初始值
const sum1 = arr.reduce(function(prev,current){
return prev + current
})
// 有初始值
const sum2 = arr.reduce(function(prev,current){
return prev + current
},10)
// 箭头函数写法
const sum3 = arr.reduce((prev, current) => prev + current, 10)
const stu = [
{
name: 'aaa',
score: 45
},
{
name: 'bbb',
score: 55
},
{
name: 'ccc',
score: 35
}
]
// 这种情况就必须要有初始值,因为数组元素是Object类型,不能直接参与运算
const sum = stu.reduce((prev, cur) => prev + cur.score, 0)
(6)find函数
find()方法返回数组中满足提供的测试函数的第一个元素的值。否则返回 undefined
const c = [1,2,3,4,14,354,655]
const num = c.find(item => item > 10)
(7)every函数
测试一个数组内的所有元素是否都能通过指定函数的测试,它返回一个布尔值。
const c = [1,2,3,4,14,354,655]
const flag = c.every(item => item < 1000) // true
除以上这些方法外,数组的方法还有很多,比如 some,concat,sort,splice,reverse,findIndex等等。
21、解构
- 数组解构
将数组中的单元值快速批量赋值给一系列变量的简洁语法
const [ a, b, c] = [ 1, 2, 3] // 等价于 a= 1, b=2, c=3 严格按照顺序
const arr = [1,2,3]
const [a, b, c] = arr
console.log(a,b,c)
多级解构
const arr = [1,2, [3,4,5]]
const [a, b, [c,d]] = arr
console.log(a,b,c, d) // 1,2,3,4
- 对象解构
const obj = {
name: '张三',
age: 21
}
const { name, age } = obj
console.log(name, age)
多级解构
const obj = {
name: '张三',
age: 21,
hobby: {
coding: 'java',
video: '动漫'
}
}
const { name, age, hobby:{ coding, video } } = obj // 需要加上内嵌的对象名
console.log(name, age, coding, video)
22、Object
Object类有三个经常使用的方法
- Object.keys
获取对象的属性的名称
<script>
const obj = {
name: 'xyz',
age: 21
}
// Object.keys
const arr1 = Object.keys(obj)
console.log(arr1) // [name, age]
</script>
- Object.values
获取对象的属性的值
// Object.values
const arr2 = Object.values(obj)
console.log(arr2) // ['xyz', 21]
- Object.assign
用于对象的拷贝,可以给对象添加属性
Object.assign(obj, { sex: 'man' })