I've looked through a bunch of references but can't find anything to address what I'm trying to do. I'm new to Javascript and JQuery, so I feel like I must be missing something.
I've created a dice roller for a D&D stats generator. The dice roller works fine:
function makeDie(sides) {
var die = function () {
return 1 + Math.random() * sides | 0;
};
die.times = function (count) {
var rolls = [];
for(var i = 0 ; i < count ; i++) {
rolls.push(this());
}
return rolls;
};
return die;
}
var dice = {
d4: makeDie(4),
d6: makeDie(6),
d8: makeDie(8),
d10: makeDie(10),
d12: makeDie(12),
d20: makeDie(20),
};
And then I can roll randomize stats (roll 4d6, discard the lowest die) from there like so:
var stat = function (){
x = dice.d6.times(4)
x = x.sort();
s = x[1] + x[2] + x[3]
return s
}
But then I want to pass the stats into an array:
var stats = [];
for (i=0; i<6; i++) {
stats.push(stat);
}
var stats = stats.sort();
But the output I get is the function printed 6 times in plaintext:
function (){ x = dice.d6.times(4) x = x.sort(); s = x[1] + x[2] + x[3] return s },
function (){ x = dice.d6.times(4) x = x.sort(); s = x[1] + x[2] + x[3] return s },
function (){ x = dice.d6.times(4) x = x.sort(); s = x[1] + x[2] + x[3] return s },
function (){ x = dice.d6.times(4) x = x.sort(); s = x[1] + x[2] + x[3] return s },
function (){ x = dice.d6.times(4) x = x.sort(); s = x[1] + x[2] + x[3] return s },
function (){ x = dice.d6.times(4) x = x.sort(); s = x[1] + x[2] + x[3] return s }
What am I missing?
-
2Missing () after stat callprogsource– progsource2015年09月25日 01:18:20 +00:00Commented Sep 25, 2015 at 1:18
3 Answers 3
You are pushing the stat function unto the array rather than the result of calling the function. You need to put () after stat like this:
var stats = [];
for (i=0; i<6; i++) {
stats.push(stat());
}
var stats = stats.sort();
Comments
You have to call stat function:
stats.push(stat());
to add arrays it returns to stats array. Without () you add the function itself to stats six times. And <function>.toString() returns the the js code of the function.
Comments
in Javascript, Functions are objects, when you call a function without the brackets like stats without (), it will pass the object and you will see the function body passed, that`s you have to call the function with brackets like stats() if you want to pass want the function returns and not the function object itself. the code will look like this then :
var stats = [];
for (i=0; i<6; i++) {
stats.push(stat());
}
var stats = stats.sort();