Javascript Data Type How to - Create array with random value








Question

We would like to know how to create array with random value.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
<!--from  ww w . j  ava  2s.  c  o  m-->
var user_arr = new Array();
for (var i=0; i<20; i++) {
    user_arr[i] = get_unique_value(user_arr);
}
function get_unique_value(array) {
    var userran = parseInt((Math.random() * (123 - 0 + 1)), 10) + 0;
    while (alreadyExists(array, userran)) {
        userran = parseInt((Math.random() * (123 - 0 + 1)), 10) + 0;
    }
    return userran;
}
function alreadyExists(array, number) {
    for (var i=0; i<array.length; i++) {
        if (array[i]==number) {
            return true;
        }
    }
}
document.writeln(user_arr);

</script>
</head>
<body>
</body>
</html>

The code above is rendered as follows: