zoukankan      html  css  js  c++  java
  • JavaScript深拷贝—我遇到的应用场景


    • 简述
      深拷贝即拷贝实例,其作用是为了不影响拷贝后的数组对起原数组造成影响。这时我们就需要进行深拷贝。(JavaScript的继承)
    • 我遇到的应用场景
      我是在用vue的element-ui做项目的时候遇到的,这是一个播放和暂停的按钮切换功能

    代码:

    图标就是代码中的a标签,下面是实现的js代码部分

       //变换播放/暂停按钮
      if (this.playClass[tagID] = 'playbtn1') {
        this.playClass[tagID] = 'playbtn';
        this.wavesurfer.play(minS, maxS);
      } else if (this.playClass[tagID] = 'playbtn') {
        this.playClass[tagID] = 'playbtn1';
        this.wavesurfer.pause(minS, maxS);
      } else {
        console.log('图标切换不成功');
      }
    

    当这样写的时候却没有效果,后来查了下,是因为element-ui本身的机制问题,本来这里是通过数组渲染出来的,我这里每次点击不同li标签里面的按钮,数组里面相应的样式也会改变,但是element-ui他的机制是要我的整个数组变化他才会渲染,就是他是渲染的整个数组,当一个元素变化的时候,他默认整个数组没变,所以不显示,所以这里我的解决方法是先把这个数组深度拷贝一份出来,监听点击的当前按钮在数组中的位置拷贝给所拷贝的数组的相应位置,改变他的值,这样的话我们就得到一个改变一个元素的数组了,然后再将这个数组赋值给原数组,那么原数组也是一个整个数组都改变的新数组,这样他就会渲染了。

    解决的代码如下:

      //深拷贝一份样式数组
      $.extend(true, showClass, this.playClass);
    
      if (this.playClass[tagID] == 'playbtn1') {
        $.extend(true, showClass[tagID], this.playClass[tagID]); //拷贝位置
        showClass[tagID] = 'playbtn';
        this.playClass = showClass;
        this.wavesurfer.play(minS, maxS);
      } else if (this.playClass[tagID] == 'playbtn') {
        $.extend(true, showClass[tagID], this.playClass[tagID]);
        showClass[tagID] = 'playbtn1';
        this.playClass = showClass;
        this.wavesurfer.pause(minS, maxS);
      } else {
        console.log('图标切换不成功');
      }
  • 相关阅读:
    测试必备基础知识总结
    初级测试工程师与高级测试工程师的区别
    调试Java程序持续占cpu问题
    Spring Struts Hibernate trouble shooting | 一些问题的记载
    MySQL 性能调优之查询优化
    Tomcat性能调优 | Tomcat Performance Tuning
    Tomcat配置、管理和问题解决 | Tomcat Configuration, Manangement and Trouble Shooting
    SWT Browser & XULRunner
    Windows应用安装制作工具调查报告
    CentOS Configuration | CentOS配置
  • 原文地址:https://www.cnblogs.com/yehui-mmd/p/9614562.html
Copyright © 2011-2022 走看看