简体   繁体   English

javascript创建一个具有options属性且该属性具有长度的对象

[英]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 jscript的新特性:如果控件由于用户选项而隐藏,则jscript错误:Uncaught TypeError:无法读取某些代码的undefined属性“ length”,否则将处理可选列表控件

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. 这将创建一个对象变量(使用新关键字),该对象变量既具有“ options”作为数组属性,又具有“ length”作为数组属性。 The script now runs without error and resolves options and options.length 脚本现在可以正常运行并且可以解析options和options.length

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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