声明无值的变量 [英] Declaring variables without a value
问题描述
我希望创建一个带有嵌套变量的Javascript对象,其中一些变量不会有指定的默认值。
我现在有这个:
var globalVarA =foo;
var globalVarB =bar;
var globalVarC;
函数myFunction(){
//做某事
}
我希望将其更改为:
var myObject = {
GlobalVars:{
globalVarA:foo,
globalVarB:bar,
globalVarC
},
myFunction:function(){
//做某事
}
}
然而,我得到以下错误:
期望的':'
如何声明这个没有值的变量?
这是最佳做法吗?还是有其他更好的解决方案?
如果要将变量定义为 GlobalVars
的属性,则必须将 undefined
明确分配给它们
GlobalVars:{
globalVarA:foo,
globalVarB:bar,
globalVarC:undefined
},
您的代码包含无效符号,使用对象文字符号时,您必须为每个变量指定一个值。这与XML或formParams等其他符号不同,您可以在不设置它的情况下声明属性/属性。
注意,在我的解决方案中,未定义变量会获得默认值 - 该值只是原始值未定义
,这是未定义的变量默认返回的值。 然而,如果您执行 globalVarC:undefined
,您的变量 p>
GlobalVars.globalVarC; //未定义
GlobalVars.globalVarX; //未定义
GlobalVars.hasOwnProperty(globalVarC ); // true
GlobalVars.hasOwnProperty(globalVarX); // false
来自规范:
4.3.9未定义值:
当变量未被赋值时使用的原始值。
I wish to create a Javascript object with nested variables where some of the variables will not have a default value specified.
I currently have this:
var globalVarA = "foo";
var globalVarB = "bar";
var globalVarC;
function myFunction(){
//do something
}
I wish to change this to:
var myObject = {
GlobalVars: {
globalVarA: "foo",
globalVarB: "bar",
globalVarC
},
myFunction: function(){
//do something
}
}
However I get the following error:
Expected ':'
How can I declare this variable without a value?
Is this the best practice or is there an alternative better solution?
If you want to define the variables as properties of GlobalVars
you have to explicitly assign undefined
to them
GlobalVars: {
globalVarA: "foo",
globalVarB: "bar",
globalVarC: undefined
},
Your code contained invalid notation, when using object literal notation you must specify a value for each variable. This is unlike other notations like XML or formParams where you can declare a attribute/property without setting it.
Note, that in my solution undefined variables do get a default value - that value is just the primitive value undefined
which is what is returned by default for variables that were not defined.
However, your variable does get defined if you do globalVarC: undefined
GlobalVars.globalVarC;//undefined
GlobalVars.globalVarX;//undefined
GlobalVars.hasOwnProperty("globalVarC");//true
GlobalVars.hasOwnProperty("globalVarX");//false
From the spec:
4.3.9 undefined value:
primitive value used when a variable has not been assigned a value.
这篇关于声明无值的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!