在JavaScript中通过索引从对象数组中获取值?

时间:2012-09-14 19:34:10

标签: javascript arrays json

这是我的目标:

var obj =
{
    salesForecast : {},
    currentWeek : 1,
    data : {
      "actual demand":  [93,87,100,63,50,76,98,140,118,64,104,104,125,131,138,91,48,64,76,99,152,93,123,127,103,97,116,45,14,80,32,120,87,128,147,74,73,135,140,71,125,163,77,78,139,59,95,108,61,101,80,85],
      "week+1":         [97,96,75,72,124,146,101,116,90,126,112,152,164,101,112,80,102,110,113,127,157,123,132,97,100,62,83,51,88,70,95,155,143,122,135,116,133,118,140,127,143,134,76,122,131,77,122,126,105,107,116,96],
      "week+2":         [107,106,83,79,136,161,111,128,99,139,123,167,180,111,123,88,112,121,124,140,173,135,145,107,110,68,91,56,97,77,105,171,157,134,149,128,146,130,154,140,157,147,84,134,144,85,134,139,116,118,128,106],
      "week+3":         [89,88,69,66,114,134,93,107,83,116,103,140,151,93,103,74,94,101,104,117,144,113,121,89,92,57,76,47,81,64,87,143,132,112,124,107,122,109,129,117,132,123,70,112,121,71,112,116,97,98,107,88],
      "week+4":         [95,94,74,71,122,143,99,114,88,123,110,149,161,99,110,78,100,108,111,124,154,121,129,95,98,61,81,50,86,69,93,152,140,120,132,114,130,116,137,124,140,131,74,120,128,75,120,123,103,105,114,94]
    }
};

我的功能:

function setPins() {
    var currentWeek = obj.currentWeek;
    console.log(currentWeek);

    var week1 = obj.data["week+1"][currentWeek],
        week2 = obj.data["week+2"][currentweek],
        week3 = obj.data["week+3"][currentweek],
        week4 = obj.data["week+4"][currentweek];

    console.log(week1);
    console.log(week2);
    console.log(week3);
    console.log(week4);
}

现在,当我呼叫setPins()时,我希望记录值96,106,88和94.我实际得到的是:

  

未捕获的ReferenceError:未定义当前周期

我在这里做错了什么?

1 个答案:

答案 0 :(得分:7)

变量名称区分大小写。您已在currentWeekcurrentweek之间进行了交替。