简体   繁体   中英

Adding elements to an array does not increments its length

I have written function which sets its arrvar variable to the received arguments. Then I have added some methods to that function:

  • setArray : adds the arguments to the end of the arrvar
  • showArray : outputs the array arrvar
  • showArrayType : outputs the type of array arrvar (which is always object)
  • showLength : outputs the length of the array arrvar

The problem here is that the length of the arrvar does not increment when I call setArray() as shown below. Why is this so?

    function ArrayClass()
    {            
        if (arguments.length != 0) {
            this.arrvar = arguments;
        }        
    }

    ArrayClass.prototype.setArray = function () {
        for (var i = this.arrvar.length, j = 0; j < arguments.length; i++, j++)
        {
            this.arrvar[i] = arguments[j];                
        }            
    }

    ArrayClass.prototype.showArray = function ()
    {
        for (var i in this.arrvar) {
            document.writeln(this.arrvar[i]+'  ');
        }
        document.writeln("<br />");
    }

    ArrayClass.prototype.showArrayType = function ()
    {
        document.writeln(typeof this.arrvar + '<br />');
    }

    ArrayClass.prototype.showLength = function()
    {
        if (this.arrvar) {
            document.writeln('Length: ' + this.arrvar.length + "<br />");
        }
    }

    var arrObj = new ArrayClass(11, 22, 33, 44);
    arrObj.showArray();  //11  22  33  44
    arrObj.showArrayType();  //object
    arrObj.showLength();  //4
    arrObj.setArray(55, 66, 77); 
    arrObj.showArray();   //11  22  33  44  55  66  77
    arrObj.showArrayType();  //object
    arrObj.showLength();  //**4**

Your problem is arguments is not an array, its some kind of array like collection. You can convert it to an array like so this.arrvar = Array.prototype.slice.call(arguments, 0); .

I wouldn't see any use of this ArrayClass function. Why don't you just use the native javascript Array Object? Anyway, your code can be a lot shorter, eg (replaced document.write with console.log here):

function ArrayClass(){            
   this.arrvar = [].slice.call(arguments) || [];
}

ArrayClass.prototype.setArray = function () {
   this.arrvar = this.arrvar.concat([].slice.call(arguments));
}

ArrayClass.prototype.showArray = function() {
   for (var i=0;i<this.arrvar.length;i+=1) {
    console.log(this.arrvar[i]);
   }
}

ArrayClass.prototype.showArrayType = function()  {
    console.log(typeof this.arrvar + '<br />');
}

ArrayClass.prototype.showLength = function() {
    console.log('Length: ' + this.arrvar.length);
}

JsFiddle demonstrating this, and demonstrating the same using native Array .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM