阵列帮助| JS

时间:2018-07-24 06:01:33

标签: javascript arrays

我对此很困惑。

我怎么能从数组中取出一个项目并输出,但是一次 它再次运行,它将在数组中选择另一个字符串。例如

const myArray = [
    'me1',
    'me2'
];

console.log(myArray); = me1
next time i run the code 
console.log(myArray); = me2,

任何想法都会很棒。谢谢

亲切的问候, 菲尔。

3 个答案:

答案 0 :(得分:0)

   // values
const myArray = [
  'me1',
  'me2'
];

// previously selected values
var history = [];

/**
 * This function return a value from myArray that isn't in  
 * the history array that store previously selected values.
 * If history array contains all the values from myArray, it
 * resets history to an empty array to start over.
 */
const nextValue = ()=>{

  if (history.length === myArray.length) history = []

  let value = null;

  for(let i=0; i<myArray.length; i++){

    const v = myArray[i];

    if (!history.includes(v)) {
      history.push(v);
      value = v;
      break;
    }
  }

  return value;
}

/**
 * Triggers nextValue()
 */
document.getElementById("button").onclick = function(){

 console.log(nextValue()) 
};

答案 1 :(得分:0)

如果您每次都想要第一项:

console.log(myArray.shift())

如果您想获得随机物品:

function random(arr){
  return Math.floor(Math.random() * arr.length)
}
for(let i = 0; i< arr.length < i++){
  let index = random(arr)
  console.log(arr[index])
  arr.splice(index, 1)
}

答案 2 :(得分:0)

您可以使用shift()方法,如下所示: while(myArray.length > 0){ console.log(myArray.shift()); }