Using $ as a key in a JS object?
Example:
console.log(myobject['media$group']);
outputs undefined
console.log(myobject['media\$group']);
outputs expected value
What's the deal? I ran into this when using youtube's API.
EDIT:
I'm confused by many of you saying it works, so I will post more info because perhaps I'm missing something stupid.
Here's the code I'm running:
console.log(feed);
console.log(feed["media$group"]["media$thumbnail"]);
Here's the object from the first log cut\pasted from firebug:
author
[Object { name={...}, uri={...}}]
category
[Object { scheme="http://schemas.google.com/g/2005#kind", term="http://gdata.youtube.com/schemas/2007#video"}, Object { scheme="http://gdata.youtube.co...mas/2007/categories.cat", term="Tech", label="Science & Technology"}, Object { scheme="http://gdata.youtube.com/schemas/2007/ke开发者_如何学运维ywords.cat", term="google"}, 10 more...]
content
Object { $t="The Google Doodle team ...googleblog.blogspot.com", type="text"}
gd$comments
Object { gd$feedLink={...}}
gd$rating
Object { average=4.77813, max=5, more...}
id
Object { $t="http://gdata.youtube.co.../api/videos/3NGSU2PM9dA"}
link
[Object { rel="alternate", type="text/html", href="http://www.youtube.com/...A&feature=youtube_gdata"}, Object { rel="http://gdata.youtube.co...as/2007#video.responses", type="application/atom+xml", href="http://gdata.youtube.co...s/3NGSU2PM9dA/responses"}, Object { rel="http://gdata.youtube.co...emas/2007#video.related", type="application/atom+xml", href="http://gdata.youtube.co...eos/3NGSU2PM9dA/related"}, 2 more...]
media$group
Object { media$category=[1], media$content=[3], more...}
published
Object { $t="2011-04-14T00:31:33.000Z"}
title
Object { $t="Charlie Chaplin Google Doodle", type="text"}
updated
Object { $t="2011-04-15T23:14:58.000Z"}
yt$statistics
Object { favoriteCount="2539", viewCount="0"}
And here's the error from the second console.log:
feed.media is undefined
[Break On This Error] console.log(feed["media"]["media"]);
'media\$group'
and 'media$group'
are equal since \$
is not a known escape sequence and thus turns into $
.
So the field simply got defined between your two calls.
Your case is interesting, I don't know why you required to escape $ character with a back slash, but these are outputs as expected.
var obj = { some$Key: 'someValue' } console.log(obj.some$Key); // someValue console.log(obj['some$Key']); // someValue
Sounds like the server escaping characters in your string. That or some other string building system has been escaping the $
character and then setting your object onto that value.
Also "foo$bar" === "foo\$bar"
It works fine.
a={'a':'test1', '$':'yes'}
console.log(a['$']); // 'yes'
Try this (jsfiddle)
精彩评论