首页 > 解决方案 > Javascript:存储最后一个值并在下次调用时增加 1

问题描述

我有一个内置于 Hype 3 的动画。我有多个场景,在每个场景的结尾我都有一个函数调用。该函数有一个场景名称数组,用于根据该数组导航到下一个场景。我已经为第一次导航工作,但是,我不确定在下次调用该函数时如何转到数组中的下一项。

正如您在下面看到的,我有一个包含两个项目的数组。调用该函数时,它会导航到第一项County1。下次调用该函数时,它应该导航到County3.

在动画结束时,我需要运行一个函数来重置位置,因为它会连续循环。

当前功能:

function nextScene() {
     var activeCounties = ['County1', 'County3'];
     hypeDocument.showSceneNamed(activeCounties[0]);
     console.log(activeCounties[0]);
}

标签: javascript

解决方案


我们可以创建一个具有自己作用域的函数,并index在这个作用域中添加属性,以跟踪应该操作的女巫场景

尝试这个

var nextScene = (function() {
    var index = 0;

    return function () {
     var activeCounties = ['County1', 'County3'];
     // hypeDocument.showSceneNamed(activeCounties[index]);
     console.log(activeCounties[index]);

     // index++ // simpliest way to manage index
     index = index + 1 === activeCounties.length ? 0 : index + 1 // circle. if index is grather than activeCounties.length than index = 0
    }
})();


nextScene() // County1
nextScene() // County3
nextScene() // County1


推荐阅读