As an exercise to help learn JS, I wrote a short bit of code that defines an array of random integers and then randomly logs one of them. Here's the code:

var turkey = true
var crud = []

for (i=0;i<10;i++)   {
    j = abs(Math.random()* 10);
    crud.push[j];
}

while (turkey)  {
    console.log(crud[abs(Math.random()*10)]);
    turkey = false;
}

This code returns a syntax error saying abs is not defined. I think I need to import a module but am not sure which one or how. Some help?

Also, if there's a more elegant way to do what I'm doing here, all input is welcome. :)

use Math.abs() instead of abs() because there is no default abs() method in js

Any point in just importing Math? It would be more overhead, but would simplify the code in the absence of other modules.

EDIT: Here's another snippet that returns a syntax error:

var oneVar = true;
var oneString;
var oneArray = [];

for (i=0;i<10;i++)   {
    j = Math.abs(Math.random() * 10);
    oneArray.push[j];
}

while (oneVar)  {
    oneString=String(oneArray[Math.abs(Math.random() * 10)]);
    oneVar = false;
}

do  {
    console.log(oneString);
}   while (oneVar);

So what's wrong with this?

Member Avatar for diafol

My solution would use the Math.random too - couldn't find a good alternative. I used this to provide an alternative other Math.* functions: http://bit.ly/TTua1H

//Function similar to range() in PHP - modded from http://bit.ly/MlBd05
Array.range = function(from, to, increment){
    var A = [];
    if(typeof from == 'number'){
        A[0]= from;
        increment = increment || 1;
        while(from + increment <= to){
            A[A.length]= from += increment;
        }
    }
    return A;
}

pool = Array.range(17,24,1); //Array 17,18,19...24
numItems = pool.length;
randomKey = Math.random() * numItems | 0; // this is the bitop

document.write('The array contains: {' + pool.join(', ') + '}<br />');
document.write('Random key: ' + randomKey + ' (0-based) and the value: ' + pool[randomKey] + '<br />');

For testing randomness, you could do soemthing like this:

pool = Array.range(17,24,1); //from the previous code - Array.range...

numItems = pool.length;
counterArray = Array();
for(i=0;i<numItems;i++)  counterArray[i] = 0;

document.write('The array contains: {' + pool.join(', ') + '}<br />');

for(i=0;i<1000;i++){
    randomKey = Math.random() * numItems | 0;
    counterArray[randomKey]++; 
    //document.write('Random key: ' + randomKey + ' (0-based) and the value: ' + pool[randomKey] + '<br />');
}

document.write('The totals of each key are: {' + counterArray.join(', ') + '}<br />');

I'm studying this code, diafol, and it uses a ton of notation I don't know. typeof I can figure out, but the double pipe means "or," doesn't it? How does that work here? The <= is something I don't know, either. The use of the pipe on line 16 is also something I don't understand. Lines 18 and 19 also seem to contain XML rather than JS. Please elaborate.

Progs

Member Avatar for diafol

Lines 18/19 are just to display to the screen

double pipe || is or to set the increment to 1 if it's not set

You can forget the Array.range bit if you want - it was just an easy way to create an array in the first place.

from + increment <= to

Just means - keep doing it until (from + increment) is less or equal to 'to'

The pipe (line 16) is the bit operator - it's a quicker way of doing:

Math.floor or Math.abs as can be seen here: http://bit.ly/TTua1H

@Proglearner, Your script is not working...

1)Line 6, j = Math.abs(Math.random() * 10);, the Math.abs() does nothing for you. The value returned from Math.random() is between 0 and 1 (a float), so it is always a positive number anyway.

2)Line 11, oneString=String(oneArray[Math.abs(Math.random() * 10)]); would almost always produce undefined. (Also Math.abs() does nothing for you either.) The reason is that Math.random() returns a float value between 0 and 1 and most likely not to be able to multiply with your selected number and produces an integer (number). An array index is an integer (number) which has no decimal. As a result, you attempt to access a non-existing array index.

// i.e.
var rand = Math.random() * 10;
// let say Math.random() returns 0.23453
// now your rand is 2.3453
// as a result, an array of array[rand] will give you "undefined" value

What you need to do is to use Math.floor() which truncates any decimal produced by the Math.random().

oneString = String(oneArray[Math.floor(Math.random()*10)])

Thanks. :) Solved.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.