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

时间:2022-02-01 07:32:31
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?

这是我的尝试,我得到一个错误,它是未定义的。我是否可以像我正在尝试的那样在Items范围内拥有变量。如果是这样,语法是什么样的?

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

我只是问这是否可以使用var variableName = {}语法来完成。

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

这里的真正目标是获取所有这些项并将其转换为键/值对的JSON数组

1 个解决方案

#1


1  

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.

顺便说一下,没有“编译器错误”,因为JavaScript不是一种编译语言,而是一种解释型语言。

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.

因为typeof返回一个字符串。检查字符串'undefined'与检查'real'undefined不同。对于字符串,它必须已明确设置为这些字符,这几乎不是这种情况。

#1


1  

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.

顺便说一下,没有“编译器错误”,因为JavaScript不是一种编译语言,而是一种解释型语言。

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.

因为typeof返回一个字符串。检查字符串'undefined'与检查'real'undefined不同。对于字符串,它必须已明确设置为这些字符,这几乎不是这种情况。