简单对象 和 数组的结构赋值
如果解构不成功,变量的值就等于undefined
对象
var { foo, bar } = { foo: "aaa", bar: "bbb" };
foo // "aaa"
bar // "bbb"
- 对象的属性没有次序,变量必须与属性同名,才能取到正确的值。
var obj = { p: ['Hello', { y: 'World' } ] };
var { p: [x, { y }] } = obj;
x // "Hello"
y // "World"
p //is not defined
注意,这时p是模式,不是变量,因此不会被赋值。
结构别名
var { foo, bar } = { foo: "aaa", bar: "bbb" };
foo // "aaa"
bar // "bbb"
// baz 为别名
var { foo: baz } = { foo: 'aaa', bar: 'bbb' };
baz // "aaa"
结构别名应用场景,
在对接接口是后端需要的参数为 key value 的形式 这个时候可以使用对象简写的方式传递传递参数,写法简便优雅
const jonFunc = () => {
return ['JavaScript', 'VUE', 'NodeJS']
}
let user = { name: '自夏', sex: '男', age: 18 }
const { name:UserName, sex, age, jon = jonFunc()} = user
Ajax.post({UserName, sex, age, jon})
// 结构使用别名后应该使用别名,不应该使用原有的变量 否则会出错
// console.log(name, sex, age, jon,hobby); //name is not defined
console.log(UserName, sex, age, jon,hobby); // 自夏 男 18 [ 'JavaScript', 'VUE', 'NodeJS' ]
注意,这时name是模式,不是变量,因此不会被赋值。
数组
var [a, b, c] = [1, 2, 3];
a //1
b //2
c //3
- 这种写法属于“模式匹配”,只要等号两边的模式相同,左边的变量就会被赋予对应的值
- 数组的元素是按次序排列的,变量的取值由它的位置决定;
let [foo, [[bar], baz]] = [1, [[2], 3]];
foo // 1
bar // 2
baz // 3
let [ , , third] = ["foo", "bar", "baz"];
third // "baz"
let [x, , y] = [1, 2, 3];
x // 1
y // 3
let [head, ...tail] = [1, 2, 3, 4];
head // 1
tail // [2, 3, 4]
let [x, y, ...z] = ['a'];
x // "a"
y // undefined
z // []
在js 中 … 可以展开数据,也可以收集数据,如果用在收集数据 必须在末尾来收集,收集的数据格式为为数组
function max (a, ...b) {
let m = [a, ...b]
return Math.max(...m)
}
console.log(max(100, 400, 500)); // 500
解构赋值允许指定默认值。
ES6内部使用严格相等运算符= = =,判断一个位置是否有值。所以,如果一个数组成员不严格等于undefined,默认值是不会生效的
var [foo = true] = [];
foo // true
var [x = 1] = [undefined];
x // 1
var [x = 1] = [null];
x // null
如果默认值是一个表达式,那么这个表达式是惰性求值的,即只有在用到的时候,才会求值。
const jonFunc = () => {
return ['JavaScript', 'VUE', 'NodeJS']
}
let user = { name: '自夏', sex: '男', age: 18 }
const { name, sex, age, jon = jonFunc() } = user
console.log(name, sex, age, jon); //自夏 男 18 [ 'JavaScript', 'VUE', 'NodeJS' ]
应用场景
当登录用户没有绑定手机号时,此时需要用户的手机号,结构用户数据时发现没有,就去调用对应的方法去绑定手机号码
函数参数的解构赋值
let getName = ({ name, xh }) => {
return `${name}我喜欢${xh}`
}
console.log(getName({ name: '自夏', xh: '喜欢喜欢'})); //自夏我喜欢喜欢喜欢
let getName = ({ name, xh } = inf) => {
return `${name}我喜欢${xh}`
}
console.log(getName({ name: '自夏', xh: '喜欢喜欢'})); //自夏我喜欢喜欢喜欢
let getName = ({ name, xh,hobby = 'Nodejs' }) => `${name}我喜欢${xh},我的爱好${hobby}`
getName({ name: '自夏', xh: '喜欢喜欢'}) //自夏我喜欢喜欢喜欢,我的爱好Nodejs
getName({ name: '自夏', xh: '喜欢喜欢',hobby:'dene'}) //自夏我喜欢喜欢喜欢,我的爱好dene
let ArrayInfo = ([x,y])=>{
return x+y
}
ArrayInfo([100,420]) // 520
Map结构
为什么是map结构? 应为Map 的存储格式是键和值 所以能够结构
如果对Map 和Set 数据结构不熟悉,前面文章有详细介绍Map 和Set
var map = new Map();
map.set('first', 'hello');
map.set('second', 'world');
for (let [key, value] of map) {
console.log(key + " is " + value);
}