我正在从站点获取一些数据并将其存储到变量中。然后,每次单击按钮时,我都会运行一个 for 循环,从该对象返回 3 个属性,并且该部分工作完美。
不同的是,每次单击按钮都会返回完全相同的数据。我不确定如何从特定对象启动 for 循环。
data: {
fetched_list: [], // the object containing the data fetched when called
list: [], // an empty list that will contain future pushed object
list_key: '0' // the last loop index
},
requestInformation(){
const temp = [];
for (let i = 0; i < 3; i++){
temp.push(this.fetched_list[i]);
}
this.list = this.list.concat(temp); // here we push the fetched data to the list
}
此时我只是不确定如何在每次单击按钮时在接下来的 3 个对象处启动 for 循环。
我试图将最后一个 i 数字保存到 list_key,但我不确定如何使用它来获取接下来的 3 个属性。
我在这里重新创建了确切的问题:https://jsfiddle.net/auq7wzuc/
最佳答案
有一些事情需要改变。
这是一个工作示例:https://jsfiddle.net/auq7wzuc/6/
基本上,以下行:
this.recipe.list_key = this.recipe.list_key++;
永远不会增加该值——它将始终为零。我们想要增加 3,所以我们应该使用:
this.recipe.list_key += 3;
此外,我们需要更改 for 循环的条件,因此它不会在 3 处停止,而是在比开始多 3 处停止。
关于javascript - 如何使用 JavaScript 的 for 循环从对象中获取接下来的 3 个项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47830436/