JavaScript数组中的JSON导致错误无法读取属性 [英] JSON in javascript array is causing error Cannot read property

查看:243
本文介绍了JavaScript数组中的JSON导致错误无法读取属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些JavaScript一年多没变了,突然就坏了.所以我首先想到的是它必须与数据相关.在查看数据时,似乎结构在一年内没有发生变化.运转了很长时间,突然间断了.

I have some javascript that hasn't changed in over a year and suddenly it's breaking. So my first thought is it must be data related. In looking at the data, it looks like the structure hasn't change in over a year. Been running fine for a long time and suddenly it's breaking.

这是我的js,使用一些JSON填充数组:

Here is my js, populating an array with some JSON:

var history = [{BillingCycleHistoryID: 339, BillingCycleDate: '7/18/2014', StartTime: '7/18/2014', PercentComplete: 100, EndTime: '7/18/2014', HoursRan: 0.16, StartedBy: 'ADMIN'}];

Chrome开发者工具栏报告此错误:未捕获类型错误:无法读取未定义的属性BillingCycleHistoryID.该错误在下面带有"value.BillingCycleHistoryID"的行上触发...

Chrome developer toolbar reports this error: "Uncaught type error: Cannot read property BillingCycleHistoryID of undefined." That error gets triggered on the line with "value.BillingCycleHistoryID" below...

if (typeof history != 'undefined') {
   $.each(history, function (key, value) {
      tbl.append(
        '<tr data-history-id="' + value.BillingCycleHistoryID + '">' +
        ....[more down here]

当我将json粘贴到jsonlint中时,它会引发一个对我没有意义的错误:

When I paste the json into jsonlint, it throws an error that makes no sense to me:

Parse error on line 2:
[    {        BillingCycleHistoryI
--------------^
Expecting 'STRING', '}'

有什么想法吗?

推荐答案

您的代码是有效的javascript,就像其他人指出的那样,并不是严格有效的JSON.

Your code is valid javascript, just not strictly valid JSON as others have pointed out.

在您的屏幕快照中,history变量看起来不正确(长度应为1).您可能只需要重命名它即可:历史记录"似乎是Chrome控制的全局变量.如果Chrome最近添加了此行为,则可以解释您的代码为何突然中断.

In your screenshot the history variable doesn't look as it should (it should have length 1). You probably just need to rename it: 'history' appears to be a global variable which Chrome controls. If Chrome has added this behaviour recently that would explain why your code suddenly broke.

请参见 http://www.javascripter.net/faq/reserved.htm

'history'并不是严格意义上的保留字,但仍然最好避免将其用作全局变量名. (而且如果可以避免使用全局变量,那是不明智的.)

'history' is not strictly speaking a reserved word, but it's still best avoided as a global variable name. (And using global variables isn't wise if you can avoid it anyway.)

这篇关于JavaScript数组中的JSON导致错误无法读取属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆