[英]generate 4 digit random number using substring
I am trying to execute below code:我正在尝试执行以下代码:
var a = Math.floor(100000 + Math.random() * 900000);
a = a.substring(-2);
I am getting error like undefined is not a function
at line 2, but when I try to do alert(a)
, it has something.我在第 2 行收到类似undefined is not a function
的错误,但是当我尝试执行alert(a)
时,它有一些东西。 What is wrong here?这里有什么问题?
That's because a
is a number, not a string.那是因为a
是一个数字,而不是一个字符串。 What you probably want to do is something like this:你可能想要做的是这样的:
var val = Math.floor(1000 + Math.random() * 9000); console.log(val);
Math.random()
will generate a floating point number in the range [0, 1) (this is not a typo, it is standard mathematical notation to show that 1 is excluded from the range). Math.random()
将在 [0, 1) 范围内生成一个浮点数(这不是一个错字,这是标准的数学符号,表明 1 被排除在范围之外)。General Case一般情况
If you want to generate an integer in the range [x, y), you can use the following code:如果要生成[x, y)范围内的整数,可以使用以下代码:
Math.floor(x + (y - x) * Math.random());
This will generate 4-digit random number (0000-9999) using substring:这将使用子字符串生成 4 位随机数 (0000-9999):
var seq = (Math.floor(Math.random() * 10000) + 10000).toString().substring(1);
console.log(seq);
$( document ).ready(function() { var a = Math.floor(100000 + Math.random() * 900000); a = String(a); a = a.substring(0,4); alert( "valor:" +a ); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
Your a
is a number.你的a
是一个数字。 To be able to use the substring
function, it has to be a string
first, try为了能够使用substring
函数,它必须先是一个string
,试试
var a = (Math.floor(100000 + Math.random() * 900000)).toString();
a = a.substring(-2);
You can get 4-digit this way .substring(startIndex, length)
, which would be in your case .substring(0, 4)
.您可以通过这种方式获得 4 位数字.substring(startIndex, length)
,在您的情况下为.substring(0, 4)
。 To be able to use .substring()
you will need to convert a
to string by using .toString()
.为了能够使用.substring()
您需要使用.toString()
将a
转换为字符串。 At the end, you can convert the resulting output into integer by using parseInt
:最后,您可以使用parseInt
将结果输出转换为整数:
var a = Math.floor(100000 + Math.random() * 900000)
a = a.toString().substring(0, 4);
a = parseInt(a);
alert(a);
https://jsfiddle.net/v7dswkjf/ https://jsfiddle.net/v7dswkjf/
The problem is that a
is a number.问题是a
是一个数字。 You cannot apply substring
to a number so you have to convert the number to a string and then apply the function.您不能将substring
应用于数字,因此您必须将数字转换为字符串,然后应用该函数。
DEMO: https://jsfiddle.net/L0dba54m/演示: https : //jsfiddle.net/L0dba54m/
var a = Math.floor(100000 + Math.random() * 900000);
a = a.toString();
a = a.substring(-2);
$(document).ready(function() {
var a = Math.floor((Math.random() * 9999) + 999);
a = String(a);
a = a.substring(0, 4);
});
// It Will Generate Random 5 digit Number & Char
const char = '1234567890abcdefghijklmnopqrstuvwxyz'; //Random Generate Every Time From This Given Char
const length = 5;
let randomvalue = '';
for ( let i = 0; i < length; i++) {
const value = Math.floor(Math.random() * char.length);
randomvalue += char.substring(value, value + 1).toUpperCase();
}
console.log(randomvalue);
I adapted Balajis to make it immutable and functional.我改编了 Balajis 以使其不可变且具有功能性。
Because this doesn't use math you can use alphanumeric, emojis, very long pins etc因为这不使用数学,所以您可以使用字母数字、表情符号、很长的别针等
const getRandomPin = (chars, len)=>[...Array(len)].map(
(i)=>chars[Math.floor(Math.random()*chars.length)]
).join('');
//use it like this
getRandomPin('0123456789',4);
function getPin() {
let pin = Math.round(Math.random() * 10000);
let pinStr = pin + '';
// make sure that number is 4 digit
if (pinStr.length == 4) {
return pinStr;
} else {
return getPin();
}
}
let number = getPin();
Just pass Length of to number that need to be generated只需将 Length of 传递给需要生成的数字
await this.randomInteger(4);
async randomInteger(number) {
let length = parseInt(number);
let string:string = number.toString();
let min = 1* parseInt( string.padEnd(length,"0") ) ;
let max = parseInt( string.padEnd(length,"9") );
return Math.floor(
Math.random() * (max - min + 1) + min
)
}
I've created this function where you can defined the size of the OTP(One Time Password):我创建了这个 function,您可以在其中定义 OTP(一次性密码)的大小:
generateOtp = function (size) {
const zeros = '0'.repeat(size - 1);
const x = parseFloat('1' + zeros);
const y = parseFloat('9' + zeros);
const confirmationCode = String(Math.floor(x + Math.random() * y));
return confirmationCode;
}
How to use:如何使用:
generateOtp(4)
generateOtp(5)
To avoid overflow, you can validate the size parameter to your case.为避免溢出,您可以根据您的案例验证 size 参数。
Numbers don't have substring method.数字没有 substring 方法。 For example:例如:
let txt = "123456"; // Works, Cause that's a string. let num = 123456; // Won't Work, Cause that's a number.. // let res = txt.substring(0, 3); // Works: 123 let res = num.substring(0, 3); // Throws Uncaught TypeError. console.log(res); // Error
For Generating random 4 digit number, you can utilize Math.random()
对于生成随机 4 位数字,您可以使用Math.random()
For Example:例如:
let randNum = (1000 + Math.random() * 9000).toFixed(0); console.log(randNum);
This is quite simple这很简单
const arr = ["one", "Two", "Three"]
const randomNum = arr[Math.floor(Math.random() * arr.length)];
export const createOtp = (): number => {
Number(Math.floor(1000 + Math.random() * 9000).toString());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.