数组解构
入门例子:
<template>
<div class="hello">
<el-row style="margin-top:10px;">
<el-col :span="12">
<el-button type="primary" @click="destructMethod">解构</el-button>
</el-col>
</el-row>
</div>
</template>
<script>
export default {
name: 'HelloWorld1',
data () {
return {
pubUserInfo: {},
}
},
watch: {},
mounted() {},
created() {},
methods: {
destructMethod() {
let [a, b, c] = [0, 1, 2];
console.log("a = " + a + " , b = " + b + " , c = " + c);
}
}
}
</script>
<style scoped></style>
- 实验1
let [a, [[b], c]] = [1, [[2], 3]];
- 实验2
let [ , , c] = ["foo", "bar", "baz"];
console.log("c = " + c);
- 实验3
let [a , , c] = ["foo", "bar", "baz"];
console.log("a = " + a);
console.log("c = " + c);
- 实验4
let [a, ...c] = [1, 2, 3, 4];
console.log(a);
console.log(c);
- 实验5
let [a, b, ...c] = [1];
console.log(a);
console.log(b);
console.log(c);
对象解构
let { x, y } = { x: 'aaa', y: 'bbb' };
alert("x = " + x + " , y = " + y);
let { z } = { x: 'aaa', y: 'bbb' };
alert(" z = " + z);
字符串解构
const [a, b, c, d, e] = 'hello';
alert(" a = " + a + ", b = " + b + ", c = " + c + ", d = " + d + ", e = " + e);
函数形参解构
export function doMethod([x, y]) {
return x + y;
}
let result = doMethod([1, 2]);
alert("result = " + result);
- 默认值解构
export function doMethod({x = 0, y = 0} = {}) {
return [x, y];
}
let result1= doMethod({x: 3, y: 8});
console.log(result1);
let result2= doMethod({x: 3});
console.log(result2);
let result3= doMethod({});
console.log(result3);
let result4= doMethod();
console.log(result4);
使用场景
使用场景1 - 变量交换
let a = 1;
let b = 2;
[a, b] = [b, a];
alert("a = " + a + " , b = " + b);
使用场景2 - 函数返回多个值的情况
- 返回数组的情况
export function doMethod() {
return [1, 2, 3];
}
let [a, b, c] = doMethod();
alert("a = " + a + " , b = " + b + " , c = " + c);
- 返回对象的情况
export function doMethod() {
return {
a: 1,
b: 2
}
}
let {a, b} = doMethod();
alert("a = " + a + " , b = " + b);
使用场景3 - 提取json数据
let jsonData = {
"name" : "sunpy",
"age" : 31,
"hobby" : ["basketball", "football"],
};
let { name, hobby } = jsonData;
console.log(name);
console.log(hobby);
使用场景4 - 引用模块的指定方法
- require方式
export function doMethod() {
console.log("execute doMethod");
}
var { doMethod } = require('@/utils/test.js');
doMethod();
- import方式
export function doMethod() {
console.log("execute doMethod");
}
import { doMethod } from '@/utils/test.js'
doMethod();
参考
https://es6.ruanyifeng.com/#docs/destructuring#%E7%94%A8%E9%80%94