2

作为 Javascript 新手,我很难弄清楚以下问题:

我有一个带有颜色列表的外部 JSON 文件。

[
{"num": "1B2-5","nam": "burntsienna","hex": "EA7E5D","com": "int2"},
{"num": "1B3-5","nam": "cadetblue","hex": "5F9EA0","col": "int1"},
{"num": "1B1-6","nam": "chartreuse","hex": "7FFF00"},
{"num": "1B2-6","nam": "chocolate","hex": "D2691E","com": "int2"}
]

在代码中的这一点上,#background 的背景颜色值将等于 JSON 文件中的值之一。我将背景颜色值转换为十六进制,删除“#”字符,并在 JSON 数组中找到它的索引号。然后我使用索引号为相应的属性声明变量。

为了这个例子的目的,我已经缩短了代码。

$(document).ready(function() {
$.getJSON('_js/json.js', function(colors_list){ 

    var pageColorPre = rgb2hex($('#background').css('background-color'));
    var pageColor = pageColorPre.toUpperCase().substr(1);
    var pageColorIndex = findIndexByKeyValue(colors_list, "hex", pageColor)

    var nameByIndex = colors_list[pageColorIndex].nam
    var numberByIndex = colors_list[pageColorIndex].num
    var comByIndex = colors_list[pageColorIndex].com


function findIndexByKeyValue(obj, key, value){
    for (var i = 0; i < obj.length; i++) {
        if (obj[i][key] == value) {
        return i;
        }
      }
      return null;
}

function rgb2hex(rgb) {
 if (  rgb.search("rgb") == -1 ) {
      return rgb;
      } else {
      rgb = rgb.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+))?\)$/);
      function hex(x) {
           return ("0" + parseInt(x).toString(16)).slice(-2);
      }
      return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]); 
      }
}
});
});

尽管代码在 Safari、Firefox 和 Chrome 中运行良好,但当浏览器到达这一行时:

  var numberByIndex = colors_list[pageColorIndex].num

调试时出现以下错误:

uncaught TypeError: cannot read property 'nam' of undefined. 

IE8 中的代码中断并显示以下消息:

'colors_list[...] nam'is null or not an object.

我想也许是因为“com”和“col”值有时为空,并不是每种颜色都有它们,这可能是个问题。但是,即使仅声明每种颜色都具有的属性,例如“nam”或“num”,我也会收到相同的错误消息。

谢谢。

4

2 回答 2

0

以为我会将其发布为新答案,因为先前的答案是指问题中似乎是错字的内容...

您得到的错误实际上与该行有关:

var nameByIndex = colors_list[pageColorIndex].nam

这就是为什么它没有到达您尝试获取NumberByIndex. (顺便说一句,你应该用分号结束这些行;,以防止进一步的问题......)

问题出在对象...

colors_list[pageColorIndex]

...因为它似乎显示为空。由于我们“知道” colors_list(尽管它可能值得调试检查)是一个有效的数组,所以问题必须是pageColorIndexfindIndexByKeyValue();最初返回的。可能findIndexByKeyValue是返回null。

值得在条件语句上方插入行console.log(obj[i][key])console.log(value)在再次运行代码时检查它们在控制台中的外观。特别注意十六进制值之前或之后的意外间距。您可能会发现该pageColor变量未按预期格式化,因此与数组对象中的任何十六进制值都不匹配并返回 null。

希望这可以帮助。

于 2013-03-28T15:28:21.717 回答
-1

更新- 根据 jcubic,这不适用于 JSON,所以我收回这个答案。

不确定这是否是您的全部问题,但您没有正确声明对象 - 键通常不是字符串。

代替:

{"num": "1B2-5","nam": "burntsienna","hex": "EA7E5D","com": "int2"}

你要:

{ num: "1B2-5", nam: "burntsienna", hex: "EA7E5D", com: "int2"}
于 2013-03-28T15:11:24.010 回答