开发者

How come it says array is undefined?

Here is a javascript sample:

var obj =
{
   options:  [],

   init:  function( )
   {
       options['one'] = 'one';
       for( k in options )
       {
          alert( optio开发者_如何学运维ns[k] );
       }
   }
};

instead of prompting "one", it says undefined, why?


You would need to reference it as obj.options.

Aside from that, you should use an object {} instead of an array [] if you're not going to be using numeric indexes.

var obj =
{
   options:  {},

   init:  function( )
   {
       obj.options['one'] = 'one';
       for( k in obj.options )
       {
          alert( obj.options[k] );
       }
   }
};

If you call the init() function from the obj reference, then you could use this inside the init function instead of obj.

var obj =
{
   options:  {},

   init:  function( )
   {
       this.options['one'] = 'one';
       for( k in this.options )
       {
          alert( this.options[k] );
       }
   }
};

obj.init();  // Makes `this` refer to `obj` in the `init` function

As @CMS noted, you should declare your variables with var. In your for loop, k is no declared with var, and as such will become a global variable.


What you're doing looks very similar, in form and concept, to something called the 'Module pattern' in javascript. It is a very powerful tool, and if you want to learn I highly recommend you read up on it.

Here is your code, rewritten as a module, with changes to avoid polluting the global scope, and to fix a potential problem with your for in loop. It also defines options as an object, rather than an array, as you seem to be using it as a hashtable rather than with numeric indices.

var module = (function() {
    //here options is private
    var options = {};

    var init = function() {
        options['one'] = 'one';
        for (var k in options) {
            if(options.hasOwnProperty(k)){
                alert(options[k]);
            }
        }
    };

    //These are the things that are public
    return {
        init:init
    };
}());


module.init();

alert(module.options); //undefined (because it's private)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜