Mat*_*att 1 javascript json tumblr
我试图通过JSON API阅读Tumblr帖子.
使用他们的API,数据传回如下:
var tumblr_api_read= {
"posts":[
"id":"1234",
"regular-title":"This is the title of the post",
"regular-body":"This is the body of the post"
]
}
Run Code Online (Sandbox Code Playgroud)
我很难回归"常规冠军"和"常规身体".
我的JS代码如下所示:
var tumblr= tumblr_api_read['posts'];
for (eachPost in tumblr)
{
var id=posts[eachPost].id; //Works fine
var regularTitle=posts[eachPost].regular-title; //Returns NaN
}
Run Code Online (Sandbox Code Playgroud)
我假设它是因为帖子[eachPost] .regular-title中有短划线但是我无法找到任何关于如何使其在这种情况下工作的文档!
谢谢.
javascript变量名称不能包含-您的示例中的特殊字符.如果您的名称中包含特殊字符的属性,则访问它的唯一方法是使用[]您用于访问posts上面对象的方法,该方法为您提供了将属性名称作为字符串传递的选项.
var regularTitle = posts[eachPost]['regular-title'];
Run Code Online (Sandbox Code Playgroud)