0

I've been searching for a solution for this but I can't seem to come up with an answer, so hoping someone on here can help.

I have this JSON string stored in a cookie like so:

$.cookie('serviceTrip', JSON.stringify(serviceTrip));

I need to extract a value from this cookie based on a certain variable "n" that changes based on user input. What I have is:

var n = 3;
var serviceTripValues = JSON.parse($.cookie('serviceTrip'));
var serviceTripStartValue = 'serviceTrip'+n+'start';
alert(serviceTripStartValue); //this produces serviceTrip3start
alert(JSON.parse($.cookie('serviceTrip')).serviceTrip3start); // this produces 12:00 as expected
alert(JSON.parse($.cookie('serviceTrip')).serviceTripStartValue); // this produces 'undefined'

I cant figure this out... I think it has something to do with the fact that serviceTripStartValue is a string and not an object but I don't know how to resolve it.

4

2 回答 2

0

您已经在解析 cookie 内容,无需重复两次:

alert(serviceTripValues[serviceTripStartValue]);

您的尝试没有成功的原因是因为您将serviceTripValues其视为这样:

serviceTripValues = {
    serviceTripStartValue:'12:00'
}

......事实上,它是这样的:

serviceTripValues = {
    serviceTrip3start:'12:00'
}

使用数组表示法允许 JavaScript 解释String存储的,serviceTripStartValue而不是将其视为文字对象键。

干杯

于 2013-06-05T19:47:58.277 回答
0

尝试这个 -

alert(JSON.parse($.cookie('serviceTrip'))[serviceTripStartValue]);
于 2013-06-05T19:46:12.700 回答