zoukankan      html  css  js  c++  java
  • JavaScript如何生成随机字母数字字符串

    如何使用javascript生成随机字母数字字符串?下面本篇文章就来给大家介绍一下使用JavaScript生成随机字母数字字符串的方法,希望对大家有所帮助。

    方法一:Math.random()方法和Math.floor()方法

    ● 创建一个函数,该函数有两个参数,一个参数是我们想要生成的字符串的长度,另一个参数是我们想要在字符串中显示的字符。

    ● 声明新变量ans = ' '。

    ● 使用for循环以相反的顺序遍历字符串。

    ● 使用JavaScript的Math.random()方法生成随机字符串。

    ● 使用JavaScript的Math.floor()方法将其四舍五入并添加到ans中。

    示例:

    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="UTF-8">
        </head>
    
        <body style="text-align:center;" id="body">
            <p id="UP" style="font-size: 19px; font-weight: bold;"></p>
            <button onClick="Fun()">点击这里</button>
            <p id="DOWN" style="color: green; font-size: 24px; font-weight: bold;"></p>
            <script>
                var up = document.getElementById('UP');
                var down = document.getElementById('DOWN');
                up.innerHTML =
                    '单击按钮,生成随机字母数字字符串';
    
                function randomStr(len, arr) {
                    var ans = '';
                    for(var i = len; i > 0; i--) {
                        ans +=
                            arr[Math.floor(Math.random() * arr.length)];
                    }
                    return ans;
                }
    
                function Fun() {
                    down.innerHTML = randomStr(20, '12345abcde');
                }
            </script>
        </body>
    </html>

    方法二:Math.random()+toString()+slice()方法

    ● 首先使用Math.random()方法生成一个随机数。

    ● 使用JavaScript toString(36)将其转换为基数36(26个字符+ 0到9),这也是一个字母数字字符串。

    ● 使用JavaScript string.slice()方法获取从位置2开始的字符串部分。

    示例:首先生成一个随机数(0-1),然后使用toString(36)方法将其转换为以36为基数的字符串,该字符串也是字母数字字符串。

    <!DOCTYPE html>
    <html>
    
        <head>
            <meta charset="UTF-8">
        </head>
    
        <body style="text-align:center;" id="body">
            <p id="UP" style="font-size: 19px; font-weight: bold;"></p>
            <button onClick="GFG_Fun()">点击这里</button>
            <p id="DOWN" style="color: green; font-size: 24px; font-weight: bold;"></p>
            <script>
                var up = document.getElementById('UP');
                var down = document.getElementById('DOWN');
                up.innerHTML =
                    '单击按钮,生成随机字母数字字符串';
    
                function GFG_Fun() {
                    down.innerHTML =
                        Math.random().toString(36).slice(2);
                }
            </script>
        </body>
    
    </html>
  • 相关阅读:
    D. Babaei and Birthday Cake--- Codeforces Round #343 (Div. 2)
    Vijos P1389婚礼上的小杉
    AIM Tech Round (Div. 2) C. Graph and String
    HDU 5627Clarke and MST
    bzoj 3332 旧试题
    codeforces 842C Ilya And The Tree
    codesforces 671D Roads in Yusland
    Travelling
    codeforces 606C Sorting Railway Cars
    codeforces 651C Watchmen
  • 原文地址:https://www.cnblogs.com/gechen/p/12229879.html
Copyright © 2011-2022 走看看