简体   繁体   中英

How can I add a array as a property with the following syntax?

var Items = {
    FormVariables: function()
    {
        if (this.array === 'undefined')
        {
           this.array = [];
        }
        return this.array;
    }
};

This was my attempt at it and I get an error of it being undefined. Can I even have variables within Items scope like I am attempting. If so, what does the syntax look like?

I am only asking if this can be done using the var variableName = {} syntax.

EDIT:

Accessing it

    var formVars = new Array();
    formVars.push('[');
    for (var item in gd["FormVariables"])
    {
        formVars.push('"' + item + '":"' + gd["FormVariables"][item] + '"');
    }
    formVars.push(']');

The real goal here is to take all these items and convert it to a JSON array of key/value pairs

Yes, you can use [] . [] is a shortcut for new Array , just like {} is for new Object .

this.array = [];

By the way, there are no 'compiler errors' since JavaScript is not a compiled language but an interpreted one.

Also, your checking does not make much sense. You'd probably want:

if (typeof this.array === 'undefined')

since typeof returns a string. Checking for the string 'undefined' is not the same as checking for 'real' undefined . For the string, it must have been set explicitly to those characters, which is almost never the case.

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