ǰλ ҳ > վ > > С

    dz̸VueΪʲôܼ䶯

    Ŀ ʱ䣺2019-11-08 09:04

    Դhttps://segmentfault.com/q/1010000015780995

    Vueݵı䶯ͨObject.definePropertyʵֵģ޷ӲǿģΪڹ캯оѾΪ󶨲

    ǹٷԭģ JavaScript ƣ Vue ܼ±䶯飺

    ֱһʱ磺 vm.items[indexOfItem] = newValue
    ޸ijʱ磺 vm.items.length = newLength

    仰ʲô˼ҲObject.definePropertyǿͨԵķԵģΪ˼

    Щ̳ϵ˵Ϊ鳤ǿɱģʹΪ5δ4Ҿģ޸lengthԪػᱻӵֵΪundefinedͨһԻȡǵֵôͽδ4أ

    Ȼ֪ijΪβܱԪزͨȫsetgetͿͬʱͼ

    Ҫ˵Ļǵܵ⣬Ԫֻ4ֵdzȷʵ1000DzΪ1000Ԫǹٷ˵JSƣ֪ʲôݣλҽ⣬л

    ⣬˵ǣȣΪ1000ֻ4Ԫص鲢һӰܣΪjsжݵıforѭforEachmapfiltersomeȣforѭ(for,for...of)ıǶԼֵıҲdzĸԪĿλб(ִлص)ҲͲģΪѭûвĻӰԺԲƣdzΪ10000ֻԪصֱʹforforEachĽ

    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

    Կdz,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ݼԴ룺

SEO