1.forEach的使用
循环遍历 修改数组
let a=["a","b","c","d","e","f"]
a.forEach((item,i)=>{
//item = item.toUpperCase();//a= ["a","b","c","d","e","f"]
a[i] = item.toUpperCase();//改变原数组中基本类型的值 a= ["A","B","C","D","E","F"]
})
console.log(a)
let b=[
{name:"zhangsan",id:1},
{name:"lisi",id:2},
]
b.forEach((item,i)=>{
//item = { name:"wangwu", id:3 } //无法改变原数组
item.name="wangwu" //可以改变原数组
})
console.log(b)
2.遍历对象键值
Object.keys()、Object.values()、Object.entries() 使用方法
const obj = { a: 1, b: 2, c: 3}
console.log(Object.keys(obj)) // 返回一个包含对象键的数组 ["a","b","c"]
console.log(Object.values(obj)) //函数来获取对象的所有属性值并将其转换成数组。[1,2,3]
console.log(Object.entries(obj)) //返回一个数组,成员是参数对象自身的属性的键值对数组 [["a",1],["b",2],["c",3]]
3.展平嵌套数组 flat()
let arrs= [["a",1],["b",2],["c",3],[{d:'a',e:2},{a:1,b:2}]]
console.log(arrs.flat())//默认展开一级,flat(n)要继续下钻n写下钻层级 ["a",1,"b",2,"c",3,{"d":"a","e":2},{"a":1,"b":2}]
4. 数组去重 new Set()、解析类数组为数组Array.from()
let arr=['123','234','345',234,"234"]
let a=new Set(arr) //类似于数组但是实际上原型是Object { "123", "234", "345", 234 }
console.log(Array.from(a)) //解析类数组为数组 ["123","234","345",234]