I am trying to create a random number as the keyName for a local storage for example in this code:
localStorage.setItem('_8bcsk999r778311o', input.value);
I want to create a random number in the place of "_8bcsk999r778311o" using javascript . Is it possible , and if possible , could you please send me the code? Thanks in advance!
CodePudding user response:
const random_id = `_${Math.random().toString(30).substr(2,17) Math.random().toString(30).substring(2,17)}`
console.log(random_id)
//localStorage.setItem(random_id, 'value goes here');
Very simple and fast solution
CodePudding user response:
Takes a number from 1 to 10 and save into number then with floor convert number to integer
//random integer from 0 to 10000:
let number = Math.floor(Math.random() * 10000);
localStorage.setItem(number, input.value);
In JavaScript, floor() is a function that is used to return the largest integer value that is less than or equal to a number. see more
Math.random() returns a random number between 0 (inclusive), and 1 (exclusive): see more
CodePudding user response:
var key = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < Math.floor(10 10*Math.random()); i ) {
key = possible.charAt(Math.floor(Math.random() * possible.length));
}
localStorage.setItem(key, input.value);
I hope this will be helpful for you. Thanks.
CodePudding user response:
You could utilise the random nature of the window.crypto
object to deliver your numeric / string IDs with a simple function as below. By tweaking the input arguments you can easily generate either numeric or alphanumeric strings of varying sizes.
const uniqid = (length = 2, base = 16) => {
let t = [];
// invoke the crypto
let crypto = window.crypto || window.msCrypto;
// create a large storage array
let tmp = new Uint32Array(length);
// populate random values into tmp array
crypto.getRandomValues( tmp );
// process these random values
tmp.forEach(i => {
t.push( Math.floor( i * 0x15868 ).toString( base ).substring( 1 ) )
});
return t.join('');
}
// purely numeric using Base10
console.info( 'Numeric - Base 10: %s', uniqid(2, 10) );
console.info( 'Long Numeric - Base 10: %s', uniqid(4, 10) );
// Alphanumeric strings using Base16
console.info( 'Alphanumeric String - Base 16: %s', uniqid(2, 16) );
console.info( 'Long Alphanumeric String - Base 16: %s', uniqid(4, 16) );