下面的函数给我一个TypeError,我试图理解为什么。基本上我有一个JSON(var测试),它是一个JSON,我正在尝试访问另一个var(blogspotter)JSON数据。对于我的脚本,blogspotter需要是一个动态JSON。如果我使用blogspotter中找到的JSON并将其复制到静态值(caseJSON)它可以工作,但如果我尝试通过var(caseVAR)来实现它,我会收到错误。
非常感谢任何帮助!
function stackerFlow (d) {
var blogspotter = getAllowedIntervals ()
/// getAllowedIntervals returns the exact JSON as found in test.caseJSON
var test = {
"caseJSON" : {"interval":{"start_month":12,"start_year":2014,"end_month":12,"end_year":2017}}
"caseVAR" : blogspotter
}
Logger.log (blogspotter) /// returns a valid JSON
Logger.log(test.caseJSON.interval.start_month) /// returns 12
Logger.log(test.caseVAR.interval.start_month) //// throws an error - "TypeError: Cannot read property "start_month" from undefined.
}
答案 0 :(得分:0)
我重新编写了一些代码,以便我可以轻松运行它。我添加了getAllowedIntervals函数,因此它按照你的说法返回blogspotter,并在“caseVar”之前添加一个逗号。 如果你将我的代码保存在test.htm之类的东西中,在mozilla中打开它,打开控制台(点击任意位置并选择“inspect element”)并点击stackerflow按钮,你可以看到它运行良好:
<html>
<head>
<script>
function getAllowedIntervals() {
return {"interval":{"start_month":12,"start_year":2014,"end_month":12,"end_year":2017}};
}
function stackerFlow () {
var blogspotter = getAllowedIntervals();
var test = {
"caseJSON" : {"interval":{"start_month":12,"start_year":2014,"end_month":12,"end_year":2017}},
"caseVAR" : blogspotter
}
console.log (blogspotter) /// returns a valid JSON
console.log(test.caseJSON.interval.start_month) /// returns 12
console.log(test.caseVAR.interval.start_month) //// throws an error - "TypeError: Cannot read property "start_month" from undefined.
}
</script>
</head>
<body>
<input type="button" onclick="stackerFlow()" value="stackerFlow"/>
</body>
</html>