본문 바로가기

Programing/JavaScript

[JavaScript] 랜덤하게 문자 만들기

참고



랜덤한 문자 5개 만들기 


function makeid()
{
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";


for( var i=0; i < 5; i++ )
text += possible.charAt(Math.floor(Math.random() * possible.length));


return text;
}




String.prototype.charAt()


var anyString = 'Brave new world';


console.log(anyString.charAt(4)); // => "e" ( === anyString[4] )
console.log(anyString.charAt(10)); // => "w" ( === anyString[10] )




Math.floor()


Math.floor( 45.95); // 45
Math.floor(-45.95); // -46




Math.random()


// 0 (포함) and 1 (불포함) 난수를 반환
function getRandom() {
return Math.random();
}


// 0 (포함) and 10 (불포함) 난수를 반환
function getRandomToTen() {
return Math.random() * 10;
} // => 2.2646899170495827








배열안의 수를 무작위로 섞어 반환


_.shuffle = function(array) {
let copied = array.slice();
//var numbers = [4, 5, 6, 7, 8, 9, 10];
for(let i = 0; i < copied.length; i++) {
let random = Math.floor(Math.random() * copied.length);
let temp = copied[random];
copied[random] = copied[i];
copied[i] = temp;
}
return copied;
};