Skip to content

通过调用fromCharCode方法来间接实现生成随机字符串 #4

@DragonFlyXD

Description

@DragonFlyXD

**方法:**String.fromCharCode(numX,numX,...,numX),参数numX为要创建字符串中字符的Unicode 编码。

例子

    function randomStr(len) {
        var result = "";
        var randomChar = function() {
            var n = Math.floor(Math.random() * 62);
            if (n < 10) return n;             //1-9
            if (n < 36) return String.fromCharCode(n + 55);     //A-Z
            return String.fromCharCode(n + 61);         //a-z
        }
        for (var i = 0; i < len; i++) {
            result += randomChar();
        }
        return result;
    }

总结:

  • 通过调用String的静态方法fromCharCode来获取具体字符串中字符unicode编码。
  • A-Z和a-z在unicode编码表中的十进制顺序分别为65-90和97-122。
  • unicode编码为ASCII编码的改进版,它们在0-127编码的字符相同。
  • charCodeAt() 方法可返回指定位置的字符的 Unicode 编码。

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions