TextBox 按数组顺序更新?

TextBox update in order from an array?

我怎样才能使文本框根据数组按顺序更新?

我在 'prices' 数组中有 5 和 10,我希望它先是 5,然后是 10,依此类推,最有效的方法是什么?现在它在数组中选择一个随机数。

const pricetext = document.getElementById('ctl00_cphPrice')
var prices = ["5", "10"]

function update() {
pricetext.value = prices[Math.floor(Math.random() * prices.length)];
}

update()

您可以使用 forEach 方法遍历数组:

let prices = ["5", "10"];
prices.forEach(function(item) {
  console.log(item); // will log 5, then 10, etc...
});

您也可以使用 for loop

您可以对索引进行闭包,并在分配和调整数组长度后递增它。

const
    pricetext = document.getElementById('ctl00_cphPrice'),
    prices = ["5", "10"],
    update = (index => () => {
        pricetext.value = prices[index++];
        index %= prices.length;
    })(0);

setInterval(update, 2000);
<input type="text" id="ctl00_cphPrice" />