简体   繁体   中英

how to handle JavaScript objects with colons in key names?

There is a syntax error in the following code:

<!DOCTYPE html>
<html>
  <body>
    Hello World!
    <script type="text/javascript">
        var obj = {'a:b': '1'};
        alert(obj.a:b); // syntax error
    </script>
  </body>
</html>

So how to handle JavaScript objects with colons in key names?

I have to do this because I need to handle a feed in jsonp format from a remote server which I do not have control over, and there are colons in the key names of the returned jsonp (because the jsonp is converted from XML with namespaces in tags).

Access them with:

obj['a:b']

The brackets are synonymous with . except they accept strings (including variables!)

So obj.x == obj['x'] , and if you had a variable foo = 'x' then obj[foo] would also be equal.

Don't let the syntax fool you, though. It may look like syntax for array access, but it is actually another way to access properties from objects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM