数组解构
let arr = [1,2,3]
let [a,b,c,d] = arr
console.log(a)
console.log(b)
console.log(c)
console.log(d)
结果1,2,3,undefined
对象解构
对象解构允许用变量的名字来匹配对象的属性,匹配成功会将对象的属性赋值给变量
let person = {
name: "cff",
age: "12",
sex: "男"
}
let {
name,
age,
sex,
addr
} = person
console.log(name)
console.log(age)
console.log(sex)
console.log(addr)
输出:cff,12,男,undefined
解构后重新命名
let person = {
name: "cff",
age: "12",
sex: "男"
}
let {
name:myname,
age:myage,
sex:mysex,
addr:myaddr
} = person
console.log(myname)
console.log(myage)
console.log(mysex)
console.log(myaddr)
输出:cff,12,男,undefined
数组解构和剩余参数结合使用
const fn = (stunents) => {
let [s1, ...s2] = stunents
console.log(s1)
console.log(s2)
}
fn(["cff", "wdm", "cxj", "yx"])
结果:cff, [“wdm”, “cxj”, “yx”]
扩展运算符
扩展运算符可以将数组或对象转为用逗号分隔的参数序列
let arr = [1,2,3]
...arr //1,2,3
扩展运算符可以用来合并数组
方法1
let arr1 = [1, 2, 3]
let arr2 = [4, 5, 6]
let arr3 = [...arr1, ...arr2, 7, 8, 9]
console.log(arr3)
结果:[1, 2, 3, 4, 5, 6, 7, 8, 9]
方法2
let arr1 = [1, 2, 3]
let arr2 = [4, 5, 6]
let arr3 = []
arr3.push(...arr1, ...arr2, 7, 8, 9)
console.log(arr3)
结果:[1, 2, 3, 4, 5, 6, 7, 8, 9]
利用扩展运算符将伪数组转换为数组
let divs = document.getElementsByTagName('div')
console.log(divs) //此时divs为类数组对象
let arry = [...divs] //将其转换为数组
console.log(arry) //此时输出的是一个真正的数组
Array.from也可以将伪数组转化为数组
let divs = document.getElementsByTagName('div')
console.log(divs) //此时divs为类数组对象
let arr = Array.from(divs) //此方法将divs转换为数组
console.log(arr)
find方法
找出一个符合条件的数组成员,没有就返回undefined
var arr = [{
name: 'cff',
id: 1
}, {
name: "cdd",
id: 2
}]
let obj = arr.find(item => item.id === 2)
console.log(obj)
findIndex方法
找到第一个符合条件的成员的索引,没有就返回-1
var arr = [{
name: 'cff',
id: 1
}, {
name: "cdd",
id: 2
}]
let i = arr.findIndex(item => item.id === 2)
console.log(i)
结果:1
includes方法
判断数组是否含有某个值,如果有返回true,否则返回false
let arr = [1,2,3]
console.log(arr.includes(1))
结果:true
字符串startWith方法
判断字符串是否以XX开头,类似的有endWIth方法判断结尾
let str = "hello world"
console.log(str.startsWith("hel"))
结果:true
字符串repeat方法
将原来的字符串重复n次返回新的字符串
let str = "hello"
console.log(str.repeat(2))
结果:hellohello
Set数据结构
Set类似于数组,但是成员的值是唯一的
const s1 = new Set([1, 2, 3])
console.log(s1)
结果: {1, 2, 3}
利用Set进行数组去重
let arr1 = ["a", "b", "b", "c", "a"]
const s = new Set(arr1)
arr1 = [...s]
console.log(arr1)
结果:[“a”, “b”, “c”]
Set的方法
add(value):添加某个值返回set结构本身
delete(value):删除某个值,返回布尔值
has(value):判断是否包含某个值,返回布尔值
clear:清除所有成员没有返回值
Set遍历取值
let arr1 = ["a", "b", "b", "c", "a"]
const s = new Set(arr1)
s.forEach(value => {
console.log(value)
})
结果:a b c