显示数组中第一个值的函数,如果再次运行,则显示数组中的第二个值

时间:2018-10-30 07:25:11

标签: javascript arrays

我想编写一个函数来获取数组的第一个值,如果我再次运行该函数,我想获取数组的第二个元素。 每当我启动该功能时,有人可以帮助我增加数组上的位置吗? 我的解决方案无效。

var nextelements = []


/*function SaveIDtoArray(clicked_id)
  {
      nextelements.push(clicked_id);
  }*/


function SaveAndProceed() {
  if (nextelements.length === 1) {
    var x = document.getElementById(nextelements[P]+"_content");
    if (x.style.display === "none") {
        x.style.display = "block";
        P++;
    } else {
        x.style.display = "none";
    }
  }
}

3 个答案:

答案 0 :(得分:1)

为什么不创建原始数组的副本并在重复的数组上运行函数。每次使用JavaScript的duplicate_array.shift()函数从重复数组中运行函数时,请始终删除第一个元素。

答案 1 :(得分:0)

使用一些全局变量,并在调用函数时对其进行递增。

data = ['a','b','c']
flag = 0

function displayArray(){
    console.log(data[flag]);
    flag++;
}

displayArray()

答案 2 :(得分:0)

您可以通过几种方式完成自己想做的事情:

使用全局标志:

如果您需要的是在第一次运行时仅做 特殊功能的函数:

let didRun = false;
function SaveAndProceed() {
  if (!didRun) {
    // Code to run the first time
    console.log('running for the first time');
    didRun = true; // remember that the function ran
  } else {
    // Code for the second run and after
    console.log('running again');
  }
}

SaveAndProceed();
// logs 'running for the first time';
SaveAndProceed();
// logs 'running again';
  

警告:using globals is generally harmful

高阶函数

为了不使用全局变量并保护自己免受意外错误的侵害,可以使用更高阶的函数(返回函数的函数)在内部存储状态:

function runner(firstTime, after) {
  let didRun = false;
  return function () {
    if (!didRun) {
      firstTime();
      didRun = true;
    } else {
      after();
    }
  }
}

const SaveAndProceed = runner(
  function firstTime() { 
    console.log('running for the first time'); 
  },
  function after() { 
    console.log('running again'); 
  }
);

SaveAndProceed();
// logs 'running for the first time';
SaveAndProceed();
// logs 'running again';

发电机

另一个受支持的选项是使用generators。生成器可能非常有用,但可能需要您支持的平台不支持。

function* GenerateSaveAndUpdate() {
   console.log('running for the first time');
   yield firstInvocationResult;
   while(true) {
     yield nextInvocationsResult;
   }
}

const SaveAndProceed = GenerateSaveAndProceed();

SaveAndProceed.next();
// logs 'running for the first time';
SaveAndProceed.next();
// logs 'running again';