How to generate id random number in js

Keywords: Javascript

Sometimes when we add new data, we need to generate primary key id automatically, and we often encounter methods that need to generate random numbers.

Here is a relatively simple method of generating random numbers:

1 //Generate random number function
2 function RndNum(n){
3     var rnd="";
4     for(var i=0;i<n;i++)
5         rnd+=Math.floor(Math.random()*10);
6     return rnd;
7 }

Then we call this method to generate random numbers in the function we need:

(the following case is used in my own project. Line 12 below calls the method RndNum written above to generate random number function, and sets 6-bit random number)

 

 1 /**
 2  * Event handling: click the add company button
 3  */
 4 function addStru(menuitem){
 5     
 6     var record=menuitem.parentMenu.record;
 7     var count=record.getCount();
 8         //var newCount =count+1;
 9     L5.MessageBox.prompt("Please enter a new company name","",function(e,corptext){
10         if(e=="ok"){
11             var data={
12                     struId:record.get("struId")+RndNum(6),//The random number function written above is called here, and the random number of splicing S001+6 bits is used
13                     struName:corptext,
14                     organId:record.get("organId")+count,
15                     parentId:record.get("organId"),
16                     sortOrder:RndNum(5)//The random number function written above is called here
17             };
18             
19             var rec=new L5.tree.TreeRecord.recordTypes["struRecord"](data,data.id);
20             record.insert(rec);
21             var command=new L5.Command("com.hrt.envir.demo.lmy5.StruSaveCommand");
22             command.setParameter("struRecord",rec);
23             command.execute("save");
24             //var a=command.getReturn("ewe");
25             var tmpe111=100;
26             if(!command.error){
27                 alert("Added successfully!")
28             }else{
29                 alert(command.error);
30             }
31         }
32     });
33 }

 

Effect verification:

 

1. Right click to add company

2. Enter the company name and click OK

3. As a result, a S001+6-bit random number id is successfully generated

Posted by ridgerunner on Sun, 08 Dec 2019 16:57:35 -0800