显示数组中的下一个对象值
Display next object value in array
我有一个包含两个对象的数组。当用户按下按钮时,我希望显示特定对象属性的下一个值。
这是我的数组:
var allQuestions = [{
question: "This is question number one",
choices: ["one", "two", "three", "four"],
correctAnswer: "two"
}, {
question: "This is question number two",
choices: ["dog", "cat", "bear", "lion"],
correctAnswer: "bear"
}];
当按下按钮时,我希望显示下一个"question"实例。
下面是切换问题的函数:
function switchQuestion() {
var singleQuestion = 0;
if(singleQuestion >= allQuestions.length) {
singleQuestion == 0;
} else {
singleQuestion == ""; // not sure what should go here
}
document.getElementById('question').innerHTML = allQuestions[singleQuestion].question;
}
您需要将问题索引的范围设置在函数之外,每次单击按钮时递增,并在超出数组边界时将其重新赋值为0:
var questionIndex = 0;
function switchQuestion() {
if(++questionIndex >= allQuestions.length) {
questionIndex = 0;
}
document.getElementById('question').innerHTML = allQuestions[singleQuestion].question;
}
在此代码中:
if(singleQuestion >= allQuestions.length) {
singleQuestion == 0;
} else {
singleQuestion == ""; // not sure what should go here
}
用=
代替==
赋值:
if (singleQuestion >= allQuestions.length) {
singleQuestion = 0;
} else {
singleQuestion = singleQuestion + 1; // increment
}
这个增量也可以用这个简短的形式来实现:
singleQuestion++;
整个表达式也可以用模数计算代替:
singleQuestion = (singleQuestion + 1) % allQuestions.length;
最后,变量singleQuestion必须在函数外部定义。
您需要将currentQuestion存储在某个地方,然后将其增量为onclick
var singleQuestion = 0;
function switchQuestion() {
if(singleQuestion >= allQuestions.length) {
singleQuestion == 0;
} else {
singleQuestion +=1;
}
document.getElementById('question').innerHTML = allQuestions[singleQuestion].question;
}
目前你会重置它回到0在每次点击不管,只显示第一个或第二个问题基于长度
下面是一个JSFiddle示例,它显示了脚本的可能实现。
我建议只用一个全局对象。
用.createElement()
代替.innerHTML()
。
var myGlobalVar = {
singleQuestion: 0,
nextButton: document.getElementById("nextQstBtn"),
questionHolder: document.getElementById("questionHolder"),
allQuestions: [qstObjOne, qstObjTwo, qstObjThree],
switchQuestion: function () {
myGlobalVar.singleQuestion += 1;
if (myGlobalVar.singleQuestion === myGlobalVar.allQuestions.length) {
myGlobalVar.singleQuestion = 0;
}
myGlobalVar.showQuestion(myGlobalVar.singleQuestion);
},
showQuestion: function (qstNum) {
// Implementation
},
init: function () {
// Script initialisation
// Attaching events, etc.
};
myGlobalVar.init();
相关文章:
- Javascript(Angular)从一个对象数组到第二个数组查找值
- jQuery$.inArray()总是返回-1和一个对象数组
- javascript处理一个对象数组以获得一个新的对象数组
- 我想遍历一个对象数组,我不想要任何重复项
- 尝试在一个对象的值和一个对象数组之间进行匹配
- Mongoose模式:强制创建一个对象数组
- 可以't分配给一个对象数组javascript
- 如何在Javascript或jQuery中在一个对象数组中重复值
- 使用jQuery.ajax请求向PHP函数发送一个对象数组
- 如何将所有复选框放入一个对象数组并标记选中的复选框
- 循环遍历JQueryUI选项卡控件中的每个选项卡,并构建一个对象数组
- 用javascript将一个对象数组复制到另一个数组中(深度复制)
- 给定一个对象数组,创建一个函数,该函数返回一个 Object,该 Object 具有按类型分组的路径数组
- 如何存储一个对象数组,这些对象是 ajax 查询从 javascript 中的 JSON 中提取数据的结果
- 当我将一个对象链接到一个对象数组时,两个对象的值是如何链接的
- ng-repeat失败,并显示一个对象数组
- 我可以使用 Lodash 来“折叠”一个对象数组吗?
- 根据属性值 lodash 将属性从对象数组合并到另一个对象数组中
- JavaScript检查一个对象数组的结果是错误的,而它应该是真的
- 给定一个对象数组,找到具有特定键的对象