Declaring variables without a value

后端 未结 3 1907
闹比i
闹比i 2021-02-09 11:12

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:

va         


        
3条回答
  •  时光说笑
    2021-02-09 11:42

    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.

提交回复
热议问题