Damon Damon - 7 months ago 20
Javascript Question

How do I reference a javascript object property with a hyphen in it?

Using this script to make a style object of all the inherited etc styles.

var style = css($(this));
alert (style.width);
alert (style.text-align);

with the following, the first alert will work fine, but the second one doesn't.. it's interpreting the
as a minus I assume.. the debugger says 'uncaught reference error'. I can't put quotes around it, though, because it isn't a string. So how do I use this object property?



Look at the comments you will see that for css properties key notation is not compatible with a number of properties. Using the camel case key notation therefore is the current way

obj.style-attr // would become 


Use key notation rather than dot


All arrays in js are objects and all objects are just associative arrays, this means you can refer to a place in an object just as you would refer to a key in an array.


or the object

obj["method"] == obj.method

a couple things to remember when accessing properties this way

  1. they are evaluated so use strings unless you are doing something with a counter or using dynamic method names.

    this means obj[method] would give you an undefined error while obj["method"] would not

  2. You must use this notation if you are using characters that are not allowed in js variables.

This regex pretty much sums it up