Javascript property from variable

后端 未结 2 1374
既然无缘
既然无缘 2021-01-28 07:26

I have a problem with my JavaScript code. I\'m starting with some more complex things right now, seemed to find some answers on the net, but unfortunately I can\'t get it fixed.

相关标签:
2条回答
  • 2021-01-28 07:40

    First of all the syntax doesn't look right. I guess the ")" after sGetMobileField: is a typo. However, what are you doing here is set a property called "sGetMobileField":

    var oFieldValues = { sGetMobileField: { Value: ValMob } };
    

    Exactly for the same reason that with Value are you set a property called "Value" and not a property that get its name from a Value variable. It is consistent, right? So you will have:

    console.log(oFieldValues.sGetMobileFields.Value) // the content of ValMob.
    

    Luckily in JS you can use the square bracked notation instead of the dot notation. It means, you can access to a property using a string. So, for instance:

    console.log("Hello");
    

    is the same of:

    console["log"]("Hello");
    

    Therefore, you can use the value of a variable to specify the property of the object to access. In your case:

    var oFieldValues = {};
    
    oFieldValues[sGetMobileField] = { Value: ValMob };
    

    Notice that following the naming convention usually used in JS, Value should be value and ValMob should be valMob.

    0 讨论(0)
  • 2021-01-28 07:41

    Try this

    var oFieldValues = { };
    oFieldValues[ sGetMobileField ] = { Value: ValMob };
    

    You can use variables as property identifiers, but not inside an object literal. You have to create the object first, and may then add dynamic properties using

    obj[ varToHoldPropertyName ] = someValue;
    
    0 讨论(0)
提交回复
热议问题