Wednesday, November 2, 2016

creating my first method. Math.floor() Math.random()

a method is something we've been using all along.  an example is:

console.log()
console is the object
.log() is the method it prints to the console anything in the ();

another example is:

document.write()
document is the object determined by javascript and the html connected to it.
write() writes info to the html document.

This is an example of writing my first method

var dice6 = { //dice6 is the object name
  sides: 6,  //it has a property with the value set to 6
  roll: function () {  // this is the declared method with an anonymous function()   
    var randomNumber = Math.floor(Math.random() * this.sides) + 1;
// this creates a local scope variable called randomNumber
// it uses some methods to help.  The Math.floor() tells it to round down.
// Math.random()  generates a random number between 0 and .999
// it is multiplied by the amount of sides that has been previously set. At sides: 6 using this.sides.
// we add one to make sure we can use use the full range 1-6
  console.log(randomNumber
  }
}

var dice100 = {
  sides: 100,
  roll: function () {
    var randomNumber = Math.floor(Math.random() * this.sides) + 1;
    console.log(randomNumber);
  }
}

No comments:

Post a Comment