ES6 对象解构、数组解构

介绍

本文是在学习ES6时做的一些学习笔记,所有的笔记请查看:ES6 学习笔记
本文视频地址:https://www.bilibili.com/video/av47304735?p=14

对象解构

主要内容都写在代码注释中:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
   const Tom={
       name: "Tom Jones",
       age: 25,
       family: {
           mother: "Norah Jones",
           father: "Richard Jones",
           brother: "Howard Jones"
       }
   }
   
   // 对象解构
   const {name,age} = Tom
   console.log(name)  //  Tom Jones
   console.log(age)  // 25
   
   //不能提前声明name 、 age,如果要声明,可以使用如下方式:
   let name= '';
   ({name,age} = Tom) //该方式声明,会被解析成代码块
    console.log(name)  //Tom Jones    
    
    // 获取mother、father 、brother 
    const{mother、father、brother} = Tom.family
    
    // 当father变量被使用了,如下所示:
    const father = "dad";
    const{mother,father : f,broter} = Tom // 对father 变量重新命名
    console.log(f) // Richard Jones
    
    // 对没有的属性,可以使用默认值
     const{mother、father、brother,sister="have no sister "} = Tom.family
     console.log(sister) // 当没有设定默认值时,会显示undefined
</script>

</body>
</html>

对象解构例子:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
  function appendChildDiv(options={}){
      const {parent="body",width='100px',height='80px',backgroundColor='pink'
      } = options;
      const div = document.createElement('div');
      div.style.width = widht;
      div.style.height= height
      dive.style.backgroundColor = backgroundColor;
      document.querySelector(parent).appendChild(div)
  }
   appendChidDiv({
       
   parent: '.container',
   width: '200px',
   height: '150px',
   backgroundColor: 'yellow'
   
   })
  
</script>

</body>
</html>

数组解构

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
  const numbers= ['one''two''three''four']
  // 获取前两个值
  const [one,two] = numbers;
  console.log(one,two) // one  two
  
  // 获取第一个和第三个值
  const[one,,three] = numbers;
  console.log(one,three)  //three
  
  // 获取第一个和后边所有的值,...others参数只能存在于最后
  const[one,...others] = numbers;
  console.log(one,others) // 获取第一个值,和后边所有值组成的一个数组
  
  // 数组解构也可以有默认值,只有当相对应的元素明确的为undefined时,才会使用
  默认值
  const details= ['JellyBool','laravist.com'];
  const [name,website,category = 'PHP'] = details;
  console.log(name,website,category)// JellyBool laravist.com PHP
</script>

</body>
</html>

数组解构应用:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
 let a=10;
let b=20;
// 交换值
[a,b]= [b,a]
console.log(a) // a 20
console.log(b) // b  10
</script>

</body>
</html>
发布了25 篇原创文章 · 获赞 18 · 访问量 1002

猜你喜欢

转载自blog.csdn.net/MoonNight608/article/details/104148537
今日推荐