JS 中解构常用方法
1.正常数组解构
let arr = ["1", undefined, "3", "4", "5", "6"] let [n1, n2 = "我是默认值", ...n5] = arr; console.log(n1) console.log(n2) console.log(n5)
拿到的结果如下
2.正常对象解构
let obj = { id: 1, name: 'name', sex: '男', age: '18', } console.log("原本的数据", obj) let { id, name } = obj console.log(id) console.log(name)
拿到的结果如下
3.数组对象解构
let arr2 = [ { name: "姓名1", age: '18' }, { name: "姓名2", age: '19' }, { name: "姓名3", age: '12' }, ] arr2.forEach(({ name, age }, index) => { console.log(name, age, index) })
拿到的结果如下
4.函数简单解构
newArrs(data) { return [data.name, data.age] }, let [onename, oneage] = this.newArrs({ name: "姓名", age: "年龄" }) console.log(onename) console.log(oneage)
拿到的结果如下
5.字符串解构 拿到指定字符串
let sstr = "我是一个渴望的字符串" let [s1, s2, ...s3] = sstr; console.log(s1) console.log(s2) console.log(s3)
拿到的结果如下