How would I give a variable a random value in javascript?
I can do this:
var myMake = ["Chevy","Subaru","Kia","Honda","Toyota"];
var x = Math.floor(Math.random() * 4 + 1);
var rand = myMake[x];
alert(rand);
which gets the desired effect, giving the variable rand a random value of one of these:
Chevy, Subaru, Kia, Honda, Toyota
but would there be a way to make a function/method that does something like this?:
var rand = randVal("Chevy", "Subaru", "Kia", "Honda", "Toyota");
Thanks!!
function randVal(){
var x = Math.floor(Math.random() * arguments.length);
return arguments[x];
}
the arguments is an array like object that refers gives a list of all supplied arguments to a function.
Just to be different!
var x = ["Chevy","Subaru","Kia","Honda","Toyota"].sort(function() {
return 0.5 - Math.random();
})[0];
alert(x);
jsfiddle
And as a function, but accepting an Array
var randMe = function ( me ) {
if ( me ) {
return me.sort(function() {
return 0.5 - Math.random();
})[0];
}
}
alert(randMe(['a','b','c']));
jsfiddle
And some prototyping as well
Array.prototype.rand = function() {
return this.sort(function() {
return 0.5 - Math.random();
})[0];
}
alert(['a','b','c'].rand());
jsfiddle
Also the actual shuffle function from here.
You can do that very easy with jQuery:
(function($) {
$.rand = function(arg) {
if ($.isArray(arg)) {
return arg[$.rand(arg.length)];
} else if (typeof arg === "number") {
return Math.floor(Math.random() * arg);
} else {
return 4; // chosen by fair dice roll
}
};
})(jQuery);
var items = ["Chevy","Subaru","Kia","Honda","Toyota"];
var item = $.rand(items);
Related
I am new to JavaScript, I have two roll functions for each roll of a frame. I am unable to get the values of each of those rolls into a frame function to call on and use. If someone could help this would be great! thanks in advance, My code is below.
var Bowling = function() {
var STARTING_TOTAL = 0;
ROLL_ONE = Math.floor(Math.random() * 11);
ROLL_TWO = Math.floor(Math.random() * 11);
this.score = STARTING_TOTAL;
var firstScore;
var secondScore;
var totalScore;
Bowling.prototype.firstRoll = function() {
firstScore = ROLL_ONE
return firstScore;
};
Bowling.prototype.secondRoll = function() {
secondScore = Math.floor(Math.random() * 11 - firstScore);
return secondScore;
};
Bowling.prototype.frameScore = function () {
totalScore = firstScore + secondScore
return totalScore;
};
};
I can only guess what you're trying to achieve. I refactored you code a little bit:
var Bowling = function () {
var STARTING_TOTAL = 0;
this.score = STARTING_TOTAL; // remains unused; did you mean "totalScore"?
this.firstScore = 0;
this.secondScore = 0;
};
Bowling.prototype.firstRoll = function () {
this.firstScore = Math.floor(Math.random() * 11);
return this.firstScore;
};
Bowling.prototype.secondRoll = function () {
this.secondScore = Math.floor(Math.random() * 11 - this.firstScore);
return this.secondScore;
};
Bowling.prototype.frameScore = function () {
this.totalScore = this.firstScore + this.secondScore
return this.totalScore;
};
// now use it like this:
var bowling = new Bowling();
console.log(bowling.firstRoll());
console.log(bowling.secondRoll());
console.log(bowling.frameScore());
In my approach however, firstScore and secondScore are public properties.
To address the question of why the second roll can be negative: as your code currently stands, if the second roll is smaller than the first roll, the result will be negative. If you want it so that if the first roll is 6, the second roll will be a number between 0 and 4, try something like:
function randomInt(maxNum) {
return Math.floor(Math.random() * maxNum)
}
var maxRoll = 11
var rollOne = randomInt(maxRoll)
var rollTwo = randomInt(maxRoll - rollOne)
console.log(rollOne)
console.log(rollTwo)
Press "Run Code Snippet" over and over again to see it work.
Changes I've made:
I made a function, randomInt that gives a random number from 0 to some max number. This saves you from needing to write the same code twice.
I created a variable maxRoll that keeps track of what the highest possible roll is.
I subtract maxRoll from the first roll to determine what the max number for the second roll should be (maxRoll - rollOne). That's then given to randomInt.
Can anyone help me to do this? The function is empty below and I am unsure how to proceed. I have the factorized number showing on the webpage now I would like the math to show before it. Something like this;
A user inputs: 3
Our site outputs: "1 x 2 x 3 = 6"
function factorialize(num) {
var total = 1;
if (num > 1) {
for (var i = 1; i <= num; i += 1) {
total *= i;
}
}
return total;
}
function showMath() {
};
$(document).ready(function() {
$("form#new-item").submit(function(event) {
event.preventDefault();
var userInput = parseInt($("input#input1").val());
var result = factorialize(userInput);
var myWork = showMath(userInput);
// var
$("#output").text(myWork + " = " + result);
});
});
You should build up an array of all the factors. Then it is easy to reduce() the array to a single value or join() it into a string.
function toFactorialArray(num){
var n = num,
arr = [n];
while (--n) arr.push(n);
return arr;
}
function getResult(arr){
return arr.reduce(
function( memo, current ) {
return memo * current
}, 1
);
}
function getWork(arr){
return arr.reverse().join(' * ');
}
$(document).ready(function() {
$("form#new-item").submit(function(event) {
event.preventDefault();
var userInput = parseInt($("input#input1").val());
var factors = toFactorialArray(userInput);
var result = getResult(factors);
var myWork = getWork(factors);
$("#output").text(myWork + " = " + result);
});
});
I am trying to create an array of four arrays.
Each of this four arrays consists of three numbers, two of them are randomly assigned from a set of numbers.
When I run the following code I don't get an error, but I also don't get a result.
What am I missing?
I don't really need the print out in console.log, this is just to check if the array is constructed correctly
var x = -2;
function createEnemy(){
var yArray = [60,145,230];
var speedArray = [30,45,55,60];
var randY = Math.floor(Math.random() * yArray.length);
var randSpeed = Math.floor(Math.random() * speedArray.length);
var enemy = [yArray[randY], speedArray[randSpeed], x];
}
function printEnemies()
{
var allEnemies = [];
(function setEnemies()
{
allEnemies.push(createEnemy());
allEnemies.push(createEnemy());
allEnemies.push(createEnemy());
allEnemies.push(createEnemy());
}());
for(var j in allEnemies)
{
for(var p in allEnemies[j] )
{
for(var i = 0; i < allEnemies[j][p].length; i++ )
{
console.log(allEnemies[j][p][i]);
}
}
}
}
printEnemies();
You forgot to return your enemy :)
function createEnemy() {
var yArray = [60,145,230];
var speedArray = [30,45,55,60];
var randY = Math.floor(Math.random() * yArray.length);
var randSpeed = Math.floor(Math.random() * speedArray.length);
var enemy = [yArray[randY], speedArray[randSpeed], x];
return enemy;
}
Make sure you return something from createEnemy:
return [yArray[randY], speedArray[randSpeed], x];
Also, you might prefer something like this loop to the nested one you've implemented:
allEnemies.forEach(function (arr) {
console.log(arr[0], arr[1], arr[2]);
});
Looks like you're missing a 'return enemy' from the createEnemy function and you have an unnecessary tertiary level loop. Here's some modified lines (with some indentation updates for readability).
CODE:
var x = -2;
function createEnemy() {
var yArray = [60,145,230];
var speedArray = [30,45,55,60];
var randY = Math.floor( Math.random() * yArray.length );
var randSpeed = Math.floor( Math.random() * speedArray.length );
var enemy = [yArray[randY], speedArray[randSpeed], x];
return enemy; // Added a return of the enemy.
}
function printEnemies() {
var allEnemies = [];
( function setEnemies() {
allEnemies.push(createEnemy());
allEnemies.push(createEnemy());
allEnemies.push(createEnemy());
allEnemies.push(createEnemy());
}()
);
for(var j in allEnemies) {
for(var p in allEnemies[j] ) {
console.log (allEnemies [j][p] ); // Removed additional depth of loop
}
}
}
printEnemies();
I am making a quick game where a player damages a enemy npc. I have a function below that does the calculation for the damage, but I can't get the console log to say i'm doing "X" amount of damage. What am I doing wrong? Instead, it just pulls up the function statement, but I want it to give me the functions value!
var damage = function() {
return Math.floor(Math.random() * 5 + 1);
};
I'm calling my function in another code properly, but when I try to console log the damage in that other code, I get a error.
function attackButton() {
darkwarrior.hp = darkwarrior.hp - damage();
console.log(darkwarrior.hp);
console.log(damage);
If you run console.log(damage()); you will get the "X" amount of damage instead of the function statement. So you could change attackButton() function to be:
function attackButton() {
var damageDealt = damage();
darkwarrior.hp = darkwarrior.hp - damageDealt;
console.log(darkwarrior.hp);
console.log(damageDealt);
I'm not sure to understand, you want to log the result? If so, you can do that:
var damage = function() {
return Math.floor(Math.random() * 5 + 1);
};
console.log(damage());
EDIT:
you forgot the (). + the value will not be the same if you don't put it in a variable:
function attackButton() {
var amount = damage()
darkwarrior.hp = darkwarrior.hp - amount;
console.log(darkwarrior.hp);
console.log(amount);
}
you just have to use an expression to assign the value to a variable. Then log it. Then return it.
var damage = function() {
var num = Math.floor(Math.random() * 5 + 1);
console.log(num);
return num;
};
damage();
Something like this should work for you.
function NPC(startingLife, name) {
this.hp = startingLife;
this.name = name
}
NPC.prototype.takeDamage = function(amount) {
this.hp = Math.max(this.hp - amount, 0);
if (this.hp == 0) {
console.log(this.name + " Dies");
}
return this.hp;
};
function damage() {
return Math.floor(Math.random() * 5 + 1);
}
var darkwarrior = new NPC(4, 'Dark Warrior');
function attackButton() {
var amount = damage();
darkwarrior.takeDamage(amount);
console.log("Dark Warrior took " + amount + " points of damage");
}
document.querySelector('#attack-button').addEventListener("click", attackButton);
<button id="attack-button">ATTACK!</button>
You are just returning the value instead of printing it. You should instead replace return with console.log(
And I am sorry to bother with this noob-stuff, but currently new to all this. But learning slowly.
In the first lines of code im getting a return (in this code i get 20*2=40. in the next phase I want to multiplie the return (40) with 20. = 800. so in the outcome it will show 40 And 800. But i only get it to be in the outbox [function], it says. and a msg; "it looks like you didnt print out a value for newNumber".
What do I do wrong? Thanks for all help!
var timesTwo = function (number) {
return number * 2;
};
timesTwo(20);
var newNumber = function (tal) {
(timesTwo * tal);
console.log(newNumber);
};
newNumber(20);
What you need to do is assign the result to a variable, and in the second function return the result:
var timesTwo = function(number) {
return number * 2;
};
var twoTimesResult = timesTwo(20);
var newNumber = function (tal) {
return twoTimesResult * tal;
};
var result2 = newNumber(20);
console.log(result2);
If you wanted to be fancy you could also do the following:
function multiplier(num, multiplier) {
var by = num * multiplier;
return function (number) {
return number * by;
};
}
var multiplyResult = multiplier(20, 2);
console.log(multiplyResult(20));
I'm answering this question too because I think these types of things are fun.
Another approach you could take is the OOP approach.
From your example you have a common multiplier of 20 and a beginning constant of 2.
I would personally attack this problem like so to avoid multiple variables:
// Create a calc object
var Calc = (function () {
// Constructor
Calc = function () {
// Initial constant
this.current_val = 2;
}
// Prototype methods
Calc.prototype = {
// inc() method
inc: function () {
return this.current_val * 20;
}
}
// Return object
return Calc;
})();
// Object Instance
var obj = new Calc();
// Initial call to inc() -> 40
obj.current_val = obj.inc();
// Log
console.log(obj.current_val);
// Second call to inc() -> 800
obj.current_val = obj.inc();
// Log
console.log(obj.current_val);
// Third call to inc() -> 16000
obj.current_val = obj.inc();
// Log
console.log(obj.current_val);
I made a jsfiddle so you can see the output.