JavaScript模拟实现深拷贝

1.通过递归

<body>
  <div id="app">
    <form @submit.prevent="insert">
      <input type="text" v-model="student.name">
      <input type="text" v-model="student.age">
      <input type="text" v-model="student.girlfrend.name">
      <button>添加</button>
    </form>

    <ul>
      <li v-for="item in list">
        姓名:{{item.name}}--
        年龄:{{item.age}}--
        女朋友:{{item.girlfrend.name}}
      </li>
    </ul>

  </div>
  <script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
  <script>
    new Vue({
      el: '#app',
      data: {
        student: {
          name: '',
          age: '',
          girlfrend: {
            name: ''
          }
        },
        list: []
      },
      methods: {
        insert() {
          let object = this.copy(this.student)
          this.list.push(object)
        },
        copy(obj) {
          let newObj = {};
          for (let i in obj) {
            if (obj[i] instanceof Object) {
              newObj[i] = this.copy(obj[i])
            } else {
              newObj[i] = obj[i]
            }
          }
          return newObj
        }
      }
    })
  </script>
</body>

2.通过JSON

  <script>
    const student1 = {
      name: '小明',
      age: 2,
      friend: {
        name: '小张',
        age: 3,
        relative:{
          father:'老张',
          age:33
        }
      }
    }

    function copy(obj){
      let str = JSON.stringify(obj);
      let newOj = JSON.parse(str)
      return newOj
    }

    const student2 = copy(student1);
    console.log(student2);
  </script>

JavaScript模拟实现深拷贝_第1张图片

你可能感兴趣的:(javascript,es6,前端)