Generate random string/characters in JavaScript

前端 未结 30 1785
闹比i
闹比i 2020-11-21 06:34

I want a 5 character string composed of characters picked randomly from the set [a-zA-Z0-9].

What\'s the best way to do this with JavaScript?

30条回答
  •  礼貌的吻别
    2020-11-21 07:22

    I know everyone has got it right already, but i felt like having a go at this one in the most lightweight way possible(light on code, not CPU):

    function rand(length, current) {
      current = current ? current : '';
      return length ? rand(--length, "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz".charAt(Math.floor(Math.random() * 60)) + current) : current;
    }
    
    console.log(rand(5));

    It takes a bit of time to wrap your head around, but I think it really shows how awesome javascript's syntax is.

提交回复
热议问题