Why does setting positions in a subclass of Array not change its length? Should I not subclass array?

前端 未结 4 1986
深忆病人
深忆病人 2021-01-19 04:56

In the CoffeeScript program below, I create a subclass of Array which sets two positions in its constructor:

class SetPositionsArray extends Arr         


        
4条回答
  •  灰色年华
    2021-01-19 05:20

    The following Array subclass, using node.js and implemented in coffeescript, works by using util.inherits & Object.defineProperty

    util = require 'util'
    
    class NGArray extends []
      constructor : ->
    
      util.inherits @, Array
    
      Object.defineProperty NGArray.prototype, "length",
        get: ->
          i = 0 
          for k,v of @
            i++ unless isNaN parseInt(k) 
          i
    
    array = new NGArray()
    array[0] = 'value'
    array[1] = true
    array[2] = ->
    array[3] = 568
    array.push(false)
    array.pop()
    
    console.log(array.length) #4
    

提交回复
热议问题