Monday 15 September 2014

Javascript Object and Properties: Adding & Accessing Properties -


I need some explanation to add properties as well as accessing objects, I'm completely new to JavaScript

I have one object:

  var device = {dev1: {"version": "1.0", "name": "air"}, dev2: { "Version": "1.0", "Name": "BE"}}   

Is this the reason why I do these two rows (I am using a browser Not using, but running on javascript as an application only Yes.)

  console.log (device.dev1 ['version']) Returns undefined console.log (device ['dev1']. Version)   

Now lets add properties ... I want to use string type property key names. Which means I do not want to look it like this. It has to follow the object described above by using the "S" dev1: {version: "1.0", name: "AIR"}

Is there any way to define asset name as string? Can this be done? var newKey = "health"; Device ['dev1']. NewKey = newValue;

Thanks a lot!

Once I fix my syntax error, your code works fine: "Device": "1.0", "name": "name": "air"}, // Added comma dev2: {"version": "1.0", "name" ":" BE "}}; Console.log (device.dev1 ['version']); // 1.0 console.log (device ['dev1']. Version); // 1.0 console.log (device.dev1.version); // 1.0

and property names are always string they can not be anything else. If it appears that the name of the property is not a string, then it is just a short story for the string.

The name of the property is a string in a variable when you can get it and for the settings: bracket syntax can be used:

  var newKey = 'someName '; Var newValue = 'woot'; Device.dev1 [newKey] = newValue; Console.log (device.dev1 [newKey]); // woot console.log (device.dev1.someName); // woot   

So if you know the property names ahead of time, then the shadowed dot property syntax is similar to obj.propName obj ['PropName'] . But if you do not know the name of the property before time, then you should use the bracket syntax. obj [propNameString]

No comments:

Post a Comment