const :
定义一个常量,必须赋初值,通常使用大写字母,常量的值不能修改,但当常量是数组或对象是,数组和对象里的元素可以修改。const 同样具有块级作用域。
数组解构:
将数组里的元素,按照一一对应的关系将值提取出来,并用变量给每个元素命名
let arr=[1,2,3]
let [a,b,c]=arr
console.log(a,b,c)
对象解构:
// 对象解构
let person = { name: '李白', age: 60 }
let { name, age } = person
console.log(name, age)
// 对象解构重命名
let {name:myName,age:myAge}=person
console.log(myName,myAge)
箭头函数:
新增的函数定义方式:()=>{}
如果函数体中只有一句代码,且代码的执行结果就是函数的返回值,可以省略大括号。
// 箭头函数:简化函数定义方式
const fn = () => {
console.log('我是箭头函数fn')
}
fn()
// 省略大括号
const sum = (a, b) => a + b
const result = sum(10, 20)
console.log(result)
// 省略小括号:形参只有一个
const FN = v => console.log(v)
FN(20)
箭头函数不绑定this关键字,箭头函数中的this指向的是箭头函数定义位置的this
剩余参数
function fn(first,...arr){
console.log(first)
console.log(arr)
}
fn(10,20,30)
let sum = (...arrs)=>{
let total=0
arrs.forEach(i => total+=i);
return total
}
console.log(sum(1,2,3,4,5,6,7,8,9,10))
console.log(sum(10,20))
扩展运算符
可以将数组拆分成以逗号分隔的参数序列
// 扩展运算符
let arr1 = ['a', 'b', 'c']
console.log(...arr1)
let arr2 = ['d', 'e', 'f']
// 方法一
// let arr3=[...arr1,...arr2]
// console .log(arr3)
// 方法二
arr1.push(...arr2)
console.log(arr1)
// 将伪数组转换成真正的数组
let divs=document.querySelectorAll('div')
divs=[...divs]
console.log(divs)
Array 的扩展方法
<!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>Array扩展方法</title>
</head>
<body>
<script>
// Array.from() 将伪数组转换为真数组
let obj = {
'name': "小明",
'age': 18,
'sex': '男',
'length': 3
}
console.log(obj)
let arr2 = Array.from(obj)
console.log(arr2)
// Array.find()查找数组中的值
let arr1 = [{ id: 1, name: '小红' }, { id: 2, name: '小李' }]
let find = arr1.find(i => i.id === 2)
console.log(find)
// findindex()查找第一个符合条件的索引,找不到,返回-1
let arr3=[0,1,2,3,4,5]
let index=arr3.findIndex((value,index)=>value>9)
console.log(index)
index=arr3.findIndex((value,index)=>value>4)
console.log(index)
// includes()判断是否包含给定的值,返回布尔值
console.log([1,2,3].includes(2))
console.log([1,2,3].includes(5))
//
</script>
</body>
</html>