我试过这个
function makeid()
{
var chars = "!~/-^";
var st = "It turns out tho, that if you append a string to the end of the URL that the CDN has never seen before, it will return the most recent version of the file. Bogus to be sure.";
var string_length = 8;
var randomstring = '';
for (var i=0; i<string_length; i++) {
var rnum = Math.floor(Math.random() * chars.length);
randomstring += chars.substring(rnum,rnum+1);
}
return randomstring;
}
var output = makeid();
console.log(output);
现在使用上面的代码生成随机字符串,如何将随机生成的字符串附加到给定字符串的随机位置。
谢谢
答案 0 :(得分:0)
这对你有什么用?
function makeid()
{
var chars = "!~/-^";
var st = "It turns out tho, that if you append a string to the end of the URL that the CDN has never seen before, it will return the most recent version of the file. Bogus to be sure.";
var string_length = 8; // did not use this.
var randomstring = '';
var randomNumber = Math.floor(Math.random()*st.length + 1);
randomstring = st.substr(0, randomNumber) + chars + st.substr(randomNumber);
return randomstring;
}
var output = makeid();
console.log(output);
这是一种不同的方式:
function makeid2()
{
var chars = "!~/-^";
var st = "It turns out tho, that if you append a string to the end of the URL that the CDN has never seen before, it will return the most recent version of the file. Bogus to be sure.";
var randomNumber = Math.floor(Math.random()*st.length + 1);
var a = st.split("");
a.splice(randomNumber,0,chars);
return a.join("");
}
var output2 = makeid2();
console.log(output2);
答案 1 :(得分:0)
使用数组对元素进行随机排序。
$(function(){
var st = "It turns out tho, that if you append a string to the end of the URL that the CDN has never seen before, it will return the most recent version of the file. Bogus to be sure.";
var array = st.split(" "),
$ele = $("#result");
for( var i=0; i<8; i++){
array = array.sort(function(){ return Math.random() -0.5 });
$ele.val( $ele.val() + "\n" + i + ": " + array.join(" ") );
}
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id='result' style="width:100%" rows="20"></textarea>
&#13;