首页 > math.random()与toString()

math.random()与toString()

console.log(Math.random().toString(16).substring(2));
console.log(Math.random().toString(36).substring(2));

上面两行代码toString起到什么作用?方法内的参数是什么意思?为什么最后会生成一个随机字符串?


Math.random()输出0到1(包括0,不包含1)的随机数。
toString(16)将随机数转换为16进制的字符串。
substring(2)截取字符串,因为随机数大于等于0小于1,前两位是“0.”,substring(2)从第三位开始截取到最后。


MDN官方文档
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Number/toString

语法

numObj.toString([radix])

参数是指定要用于数字到字符串的转换的基数(从2到36)。
如果未指定 radix 参数,则默认值为 10。

【热门文章】
【热门文章】