Random char in a .js file
This is the chars: "*+-/";
Javascript getElementById
How can i do "randt"
to be 1 random char?
So if i type:
document.getElementById("sms-text").innerHTML = "" + random2 开发者_StackOverflow+ randt;
It will be for ex "22*"
or "51+"
How do i do it?
If I understand your question correctly, you will take a random number 0-3, then find the character at that position;
var signs = "*+-/";
var signId = Math.floor(Math.random() * signs.length);
var sign = signs.charAt(signId);
var str = "*+-/";
var random_char = str[Math.floor(Math.random() * str.length)];
As the other answers point out, str.charAt()
would also work.
This is pretty simple to do with a combination of Math.random()
and Math.floor()
:
var chars = "*+-/",
randt = chars[Math.floor(Math.random() * 4)];
Note that you could replace 4
with chars.length
if you don't know how many characters are in chars
.
Simply just grab a random number from 0 to the length of the string and then cut the char out like so
var chars = "+-/";
var char = chars[Math.floor(Math.random() * chars.length)];
using char
would be the random character
alternatively you can add the rand method to the prototype like so
String.prototype.randChar = function()
{
return this[Math.floor(Math.random() * this.length)];
}
and then within any string created you can use like so
char = "+-.".randChar();
This is basically the same question as you asked before, only with the difference that you are using innerHTML
instead of document.write
. The way to produce the string is the same, so you can just use the function from my previous answer:
function makeid(lastNumber) {
var possible = "*+-/";
return lastNumber + possible.charAt(Math.floor(Math.random() * possible.length));
}
Usage:
document.getElementById("sms-text").innerHTML = makeid(random2);
var randt=['*','+','-','/'][Math.floor(Math.random()*4)];
精彩评论