[英]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.
我甚至可以像我尝试的那样在Items范围内拥有变量。 If so, what does the syntax look like?
如果是这样,语法是什么样的?
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数组
Yes, you can use []
. 是的,您可以使用
[]
。 []
is a shortcut for new Array
, just like {}
is for new Object
. []
是new Array
的快捷方式,就像{}
是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. 因为
typeof
返回一个字符串。 Checking for the string 'undefined'
is not the same as checking for 'real' undefined
. 检查字符串
'undefined'
与检查' undefined
。 For the string, it must have been set explicitly to those characters, which is almost never the case. 对于字符串,必须已将其显式设置为这些字符,几乎从来没有这样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.