简体   繁体   English

如何检查集合中使用了哪个变量?

[英]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.

相关问题 如何从JavaScript文件检查正在使用哪个HTML? - How to check which HTML is being used from JavaScript file? 如何检查是否未定义变量,并显示一个错误向我显示哪个变量? - How do I check if a variable isnt defined, throw an error that shows me which variable? 如何捕获用于访问网页的浏览器? - How do I capture the browser being used to access a webpage? 如何防止谷歌API被他人使用? - How do I prevent the Google API from being used by others? 如何在Rails上检查javascript变量? - How do i check javascript variable on Rails? 如何检查变量是否是 JavaScript 中的数组? - How do I check if a variable is an array in JavaScript? 如何检查车把中的变量是否为假? - How do I check if a variable is falsey in handlebars? 如何使用 lodash 中的 includes 方法检查对象是否在集合中? - How do I use the includes method in lodash to check if an object is in the collection? 如何检查集合中是否存在文档 (Firebase REACT)? - How do I check if a document exists within a collection (Firebase REACT)? 如何检查 JS 中的 firestore(不是文档)中是否存在集合 - How do I check if collection exist in firestore (not document) in JS
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM