你好,我需要用一个新的变量(Z)判断过go 的z变量,请帮助

你好,这是我得到的

<html>
    <head>
        <link rel = "stylesheet" href = "style.css">
    </head>
    <body onload = "myFunction()" id = "body">
        <div id = 'play_ground'>
        </div>
        <b2>PLAY<b2>
        <script src = "Game-9.js"></script>
    </body>
</html>
var play_box = document.getElementById('play_ground');
function myFunction(){
    for (i = 1; i <= 9; i++){
        var z = Math.floor(Math.random() * 10)
             play_box.innerHTML += '<div class = "box">'+ z +'</div>' };
        }
}

我只是不能想象我怎么才能用一个新的变量(Z)判断过go 的z变量,请帮帮忙

推荐答案

您可以使用Fisher-Yates随机算法Fisher-Yates shuffle algorithm wikipedia修改代码以生成从1到9的唯一随机数.以下是您的代码的更新版本:

<script>
var play_box = document.getElementById('play_ground');
var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];

function myFunction(){
    shuffle(numbers);
    for (var i = 0; i < 9; i++){
        play_box.innerHTML += '<div class="box">'+ numbers[i] +'</div>';
    }
}

function shuffle(array) {
    for (var i = array.length - 1; i > 0; i--) {
        var j = Math.floor(Math.random() * (i + 1));
        var temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
}
</script>
<html>
    <head>
        <link rel = "stylesheet" href = "style.css">
    </head>
    <body onload = "myFunction()" id = "body">
        <div id = 'play_ground'>
        </div>
        <b2>PLAY<b2>
        <script src = "Game-9.js"></script>
    </body>
</html>

在这个更新的代码中,数组Numbers最初用于存储从1到9的数字.然后调用Shuffle函数以随机顺序对数组进行随机置乱.最后,在myFunction函数中,随机数组用于为div生成随机数,确保每个数在输出中只出现一次.

Javascript相关问答推荐

使脚本兼容于其他YouTube URL格式

详细说明如何以图表方式改变仪表的范围和 colored颜色

想要检测字符串中的所有单词

Angular material 表多个标题行映射

如何在NightWatch.js测试中允许浏览器权限?

如何通过在提交时工作的函数显示dom元素?

React:未调用useState变量在调试器的事件处理程序中不可用

Klaro与Angular的集成

在网页上添加谷歌亵渎词

加载背景图像时同步旋转不显示的问题

PDF工具包阿拉伯字体的反转数字

这个值总是返回未定义的-Reaction

TypeError:无法分解';React2.useContext(...)';的属性';basename';,因为它为空

使用js构造一个html<;ath&>元素并不能使其正确呈现

类构造函数忽略Reaction Native中的可选字段,但在浏览器中按预期工作

为什么可选参数的顺序会导致问题?

<;img>;标记无法呈现图像

Google脚本数组映射函数横向输出

无法设置RazorPay订阅API项目价格

用于测试其方法和构造函数的导出/导入类