es2015之解构赋值

代码

<script>
window.onload = function (){
  // 解构数组
  let [a,b,c] = [1,2,3];
  console.log("解构数组--" + a,b,c);
  // 解构json
  let json = {
    name:"Tom",
    age:"20",
    job:"码畜"
  }
  let {name,age,job} = json;
  console.log("解构json--" + name,age,job);
  // 解构json并起别名
  let {name:n,age:g,job:j} = json;
  console.log("解构json并起别名--" + n,g,j);
  // 设置默认值
  let [x,y,z='暂无数据'] = [1,2];
  console.log("设置默认值--" + x,y,z);
  // 数组倒序
  let a1 = 12;
  let a2 = 5;
  [a1,a2] = [a2,a1];
  console.log("数组倒序--" + a1,a2);
  // 函数返回的对象进行解构
  function getPos(){
    return {
      left:10,
      top:20
    }
  }
  let {left,top:t} = getPos();
  console.log("函数返回的对象进行解构--" + left,t);
  // 调用函数解构对象
  function show({a,b="默认数据"}){
    console.log("调用函数解构对象--" + a,b);
  }
  show({
    a:"我是a"
  })
}
</script>

结果

[HMR] Waiting for update signal from WDS...
(index):24 解构数组--1 2 3
(index):32 解构json--Tom 20 码畜
(index):35 解构json并起别名--Tom 20 码畜
(index):38 设置默认值--1 2 暂无数据
(index):43 数组倒序--5 12
(index):52 函数返回的对象进行解构--10 20
(index):55 调用函数解构对象--我是a 默认数据
Last modification:June 9th, 2019 at 02:22 pm
If you think my article is useful to you, please feel free to appreciate

Leave a Comment