[英]How do I check which variable in a collection is being used?
I'm trying to work a script to check if a called variable is currently being used. 我正在尝试使用脚本来检查当前是否正在使用被调用的变量。 Here is an example of the code. 这是代码示例。
function tellAJoke()
{
var collective = ["variable 1",
"Variable 2",
"Variable 3",
"Variable 4"]
var destination = document.getElementById('destination')
destination.innerHTML = collective[Math.floor(Math.random() * collective.length)];
}
How would I check which variable is being used? 如何检查正在使用哪个变量? This is to prevent the same variable from being called again. 这是为了防止再次调用同一变量。
Instead of trying to find a new value each time, just shuffle your array randomly on page load and then iterate over it. 不必每次尝试寻找新值,只需在页面加载时随机地对数组进行洗牌,然后对其进行迭代即可。 This way you will have a different order each time the page gets loaded but you'll never show the same thing twice in a row. 这样,每次加载页面时,您将拥有不同的顺序,但是您永远不会连续两次显示相同的内容。 If you are done with the array, simply start from the beginning 如果完成数组操作,只需从头开始
small example: http://jsfiddle.net/Elak/8JsD4/ 小例子: http : //jsfiddle.net/Elak/8JsD4/
var collective = ["variable 1",
"Variable 2",
"Variable 3",
"Variable 4"]
var shuffle = function (arr) {
for (var j, x, i = arr.length; i; j = parseInt(Math.random() * i), x = arr[--i], arr[i] = arr[j], arr[j] = x);
return arr;
}
var newCol = shuffle(collective);
var index = 0;
setInterval(function () {
if (index >= newCol.length) index = 0;
$("#out").text(newCol[index]);
index++;
}, 1000);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.