gpt4 book ai didi

javascript - 使用参数动态引用json对象

转载 作者:行者123 更新时间:2023-11-27 23:46:19 24 4
gpt4 key购买 nike

我得到:

Uncaught TypeError: Cannot read property '0' of undefined

尝试使用参数动态引用 javascript 对象时。虽然当我尝试传递单个参数 virtual_page_no 时它正在工作,但在传递 2 个参数时它开始给出错误。

// Json list
var patients = {
"patient_1": [
{
"page_no": "3",
"quest_response_headline": "Question1",
"quest_response": "Response1",
"quest_next_link": "View Answer"
},
{
"page_no": "4",
"quest_response_headline": "Question2",
"quest_response": "Response2",
"quest_next_link": "Next Question >"
}
]
}

var current_virtual_page = 0;
var next_virtual_page = current_virtual_page + 1;

function quest_response_text(i, virtual_page_no) {
var quest_response_headline = patients.patient_i[virtual_page_no].quest_response_headline;
var quest_response = patients.patient_i[virtual_page_no].quest_response;
var quest_next_link = patients.patient_i[virtual_page_no].quest_next_link;

$('.quest-response-headline').text(quest_response_headline);
$('.quest-response').text(quest_response);
$('.quest-next-link').text(quest_next_link);
}

// init
quest_response_text(1, current_virtual_page);

// When user click on view answer or next question link
$('.quest-next-link').on('click', function () {
quest_response_text(next_virtual_page);
});

最佳答案

如果您想使用 i 变量动态访问 患者.病人_1,请尝试使用:

patients['patient_' + i]

所以它应该看起来像:

var quest_response_headline = patients['patient_' + i][virtual_page_no].quest_response_headline;

关于javascript - 使用参数动态引用json对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33146584/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com