简体   繁体   中英

javascript create an object which has an options property and that proerty has a length

Problem I have a list control which may or may not be (visible) on a web page. New to jscript so: If the control is hidden because of a user option, then the jscript error with: Uncaught TypeError: Cannot read property 'length' of undefined for some code which would otherwise handle the optional list control

I have a class:

function EmptyList()
{
this.options = [];
return this.options;
}

and I assign it so

dropdownlist = document.getElementById("<%=optionalList.ClientID%>");
if (dropdownlist == 'undefined') {
  // hidden so does not exist client side
  // give it the right type but never call it
  dropdownlist = new EmptyList();
 }
else if (dropdownlist == null) {
  // hidden so does not exist client side
  // give it the right type but never call it
  dropdownlist = new EmptyList();
 }

I used to have an error saying options could not be read... so this seems to be in the right direction but I thought all arrays had a length...

Thanks

The problem was solved by changing the definition of empty object to:

   function EmptyList()
    {
        var self = this;
        self.options = [];
        self.options.length = 0;  
    }

This created (with the new key word) an object variable with both 'options' as an array property and 'length' as a property of the array. The script now runs without error and resolves options and options.length

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