µ±Ç°Î»Öà Ö÷Ò³ > ÍøÕ¾¼¼Êõ > ´úÂëÀà >

    dz̸VueΪʲô²»Äܼì²âÊý×é±ä¶¯

    À¸Ä¿£º´úÂëÀà ʱ¼ä£º2019-11-08 09:04

    ÎÊÌâÀ´Ô´£ºhttps://segmentfault.com/q/1010000015780995

    ÎÊÌâÃèÊö£ºVue¼ì²âÊý¾ÝµÄ±ä¶¯ÊÇͨ¹ýObject.definePropertyʵÏֵģ¬ËùÒÔÎÞ·¨¼àÌýÊý×éµÄÌí¼Ó²Ù×÷ÊÇ¿ÉÒÔÀí½âµÄ£¬ÒòΪÊÇÔÚ¹¹Ô캯ÊýÖоÍÒѾ­ÎªËùÓÐÊôÐÔ×öÁËÕâ¸ö¼ì²â°ó¶¨²Ù×÷¡£

    µ«Êǹٷ½µÄÔ­ÎÄ£ºÓÉÓÚ JavaScript µÄÏÞÖÆ£¬ Vue ²»Äܼì²âÒÔϱ䶯µÄÊý×飺

    µ±ÄãÀûÓÃË÷ÒýÖ±½ÓÉèÖÃÒ»¸öÏîʱ£¬ÀýÈ磺 vm.items[indexOfItem] = newValue
    µ±ÄãÐÞ¸ÄÊý×éµÄ³¤¶Èʱ£¬ÀýÈ磺 vm.items.length = newLength

    Õâ¾ä»°ÊÇʲôÒâ˼£¿ÎÒ²âÊÔÁËÏÂObject.definePropertyÊÇ¿ÉÒÔͨ¹ýË÷ÒýÊôÐÔÀ´ÉèÖÃÊôÐԵķÃÎÊÆ÷ÊôÐԵģ¬ÄÇΪºÎ×ö²»Á˼àÌý£¿

    ÓÐЩÂÛ̳ÉϵÄÈË˵ÒòΪÊý×鳤¶ÈÊǿɱäµÄ£¬¼´Ê¹³¤¶ÈΪ5£¬µ«ÊÇδ±ØÓÐË÷Òý4£¬ÎÒ¾ÍÏëÎÊÎÊÕâ¸ö´ð°¸ÄÄÀïÀ´µÄ£¬ÐÞ¸Älength£¬ÐÂÔöµÄÔªËػᱻÌí¼Óµ½×îºó£¬ËüµÄֵΪundefined£¬Í¨¹ýË÷ÒýÒ»Ñù¿ÉÒÔ»ñÈ¡ËûÃǵÄÖµ£¬Ôõô¾Í½Ð×ö¡°Î´±ØÓÐË÷Òý4¡±ÁËÄØ£¿

    ¼ÈȻ֪µÀÊý×éµÄ³¤¶ÈΪºÎ²»ÄܱéÀúËùÓÐÔªËز¢Í¨¹ýË÷ÒýÕâ¸öÊôÐÔÈ«²¿Ìí¼ÓsetºÍget²»¾Í¿ÉÒÔͬʱ¸üÐÂÊÓͼÁËÂð£¿

    Èç¹û·ÇҪ˵µÄ»°£¬¿¼Âǵ½ÐÔÄܵÄÎÊÌ⣬¼ÙÉèÔªËØÄÚÈÝÖ»ÓÐ4¸öÓÐÒâÒåµÄÖµ£¬µ«Êdz¤¶Èȷʵ1000£¬ÎÒÃDz»¿ÉÄÜΪ1000¸öÔªËØ×ö¼ì²â²Ù×÷¡£µ«Êǹٷ½ËµµÄÓÉÓÚJSÏÞÖÆ£¬ÎÒÏëÖªµÀÕâ¸öÏÞÖÆÊÇʲôÄÚÈÝ£¿¸÷λ´ó´ó°ïÎÒ½â¾öÏÂÕâ¸öÎÊÌ⣬¸ÐлÍò·Ö

    Ãæ¶ÔÕâ¸öÎÊÌ⣬ÎÒÏë˵µÄÊÇ£¬Ê×ÏÈ£¬³¤¶ÈΪ1000£¬µ«Ö»ÓÐ4¸öÔªËصÄÊý×é²¢²»Ò»¶¨»áÓ°ÏìÐÔÄÜ£¬ÒòΪjsÖжÔÊý¾ÝµÄ±éÀú³ýÁËforÑ­»·»¹ÓÐforEach¡¢map¡¢filter¡¢someµÈ£¬³ýÁËforÑ­»·Íâ(for,for...of)£¬ÆäËûµÄ±éÀú¶¼ÊǶԼüÖµµÄ±éÀú£¬Ò²¾ÍÊdzýÁËÄÇËĸöÔªËØÍâµÄ¿Õλ²¢²»»á½øÐбéÀú(Ö´Ðлص÷)£¬ËùÒÔÒ²¾Í²»»áÔì³ÉÐÔÄÜËðºÄ£¬ÒòΪѭ»·ÌåÖÐûÓвÙ×÷µÄ»°£¬Ëù´øÀ´µÄÐÔÄÜÓ°Ïì¿ÉÒÔºöÂÔ²»¼Æ£¬ÏÂÃæÊdz¤¶ÈΪ10000£¬µ«Ö»ÓÐÁ½¸öÔªËصÄÊý×é·Ö±ðʹÓÃfor¼°forEach±éÀúµÄ½á¹û£º

    var arr = [1]; arr[10000] = 1
    function a(){
      console.time()
      for(var i = 0;i<arr.length;i++)console.log(1)
      console.timeEnd()
    }
    a(); //default: 567.1669921875ms
    a(); //default: 566.2451171875ms
    
    function b(){
      console.time()
      arr.forEach(item=>{console.log(2)})
      console.timeEnd()
    }
    b(); //default: 0.81982421875ms
    b(); //default: 0.434814453125ms

    ¿ÉÒÔ¿´µ½½á¹û·Ç³£Ã÷ÏÔ,²»¹ý£¬Èç¹ûforÑ­»·Öв»×ö²Ù×÷µÄ»°Á½ÕßËٶȲ¶à

    Æä´Î£¬ÎÒҪ˵µÄÊÇ£¬ÎÒÒ²²»ÖªµÀÕâ¸öÏÞÖÆÊÇʲô (⇀‸↼‶) ¨r( •́¦Ø•̀ )¨q

    Object.defineProperty() ·½·¨»áÖ±½ÓÔÚÒ»¸ö¶ÔÏóÉ϶¨ÒåÒ»¸öÐÂÊôÐÔ£¬»òÕßÐÞ¸ÄÒ»¸ö¶ÔÏóµÄÏÖÓÐÊôÐÔ£¬ ²¢·µ»ØÕâ¸ö¶ÔÏó¡£Êý×éµÄË÷ÒýÒ²ÊÇÊôÐÔ£¬ËùÒÔÎÒÃÇÊÇ¿ÉÒÔ¼àÌýµ½Êý×éÔªËصı仯µÄ

    var arr = [1,2,3,4]
    arr.forEach((item,index)=>{
      Object.defineProperty(arr,index,{
        set:function(val){
          console.log('set')
          item = val
        },
        get:function(val){
          console.log('get')
          return item
        }
      })
    })
    arr[1]; // get 2
    arr[1] = 1; // set 1

    µ«ÊÇÎÒÃÇÐÂÔöÒ»¸öÔªËØ£¬¾Í²»»á´¥·¢¼àÌýʼþ£¬ÒòΪÕâ¸öÐÂÊôÐÔÎÒÃDz¢Ã»ÓмàÌý£¬É¾³ýÒ»¸öÊôÐÔÒ²ÊÇ¡£

    Ôٻص½ÌâÖ÷µÄÎÊÌ⣬¼ÈÈ»Êý×éÊÇ¿ÉÒÔ±»¼àÌýµÄ£¬ÄÇΪʲôvue²»Äܼì²âvm.items[indexOfItem] = newValueµ¼ÖµÄÊý×éÔªËظıäÄØ£¬ÄÄÅÂÕâ¸öϱêËù¶ÔÓ¦µÄÔªËØÊÇ´æÔڵģ¬ÇÒ±»¼àÌýÁ˵ģ¿

    ΪÁ˸ãÇå³þÕâ¸öÎÊÌ⣬ÎÒÓÃvueµÄÔ´Âë²âÊÔÁËÏ£¬ÏÂÃæÊÇvue¶ÔÊý¾Ý¼à²âµÄÔ´Â룺