TextBox从数组顺序更新?

时间:2019-03-08 19:57:31

标签: javascript tampermonkey

我如何能够做到使TextBox根据数组顺序更新?

我在“价格”数组中有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()

2 个答案:

答案 0 :(得分:2)

您可以对索引进行封闭处理,然后在分配并调整数组的长度后将其递增。

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" />

答案 1 :(得分:0)

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

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

您也可以使用for loop进行此操作。