0

I have created a dice function that trows random dices and sum the value of them.

Now every number from 0-9 is connected to a class, so if i get number 4 it should call class " four" So i created a switch from 0-9 . But when i get a sum more than 9 its give me the default number, since the function dosent know that 11 is actually 2 numbers. I was wonder I its possible to split the numbers and put them into an array so when i pass it to the switch it gets med "one" "one" .

Any ideas ?

var value = total;
    switch(this.value){
        case 1:
            value ="one";
            break
        case 2:
            value ="two";
            break
        case 3:
            value ="three";
            break
        case 4:
            value ="four";
            break
        case 5:
            value ="five";
            break
        case 6:
            value ="six";
            break
        case 7:
            value ="seven";
            break
        case 8:
            value ="eight";
            break
        case 9:
            value ="nine";
            break
        case 0:
            value ="zero";
            break
        default:
            value ="zero" 
    }
Dymond
  • 2,158
  • 7
  • 45
  • 80
  • well, its more like. When i get the sum 11, I would like to call the switch by class "one" + "one" otherwise i would need a endless combinations of numbers to call every sum. – Dymond Feb 09 '13 at 14:13

2 Answers2

1

You could use the string split function for that:

var result = this.value.toString(10).split("").map(function(digit) {
    return ["zero", "one", "two", "three", "four", "five",
            "six", "seven", "eight", "nine"][digit];
});

(Of course you can use a loop instead of map; Check this answer and its comments on how the array thing works)

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • @Dymond: Ah, wait, you're neither switching on the `total` nor on the `value` variable, but on the `this.value` property. – Bergi Feb 09 '13 at 14:47
0

You can use split() after you transformed your number to a string. Then run through the resulting array and assign your classes.

var total = 11;

var pieces = ("" + total).split( "" );

for( var i=0; i<pieces.length; i++) {
  // your switch in here
}
Sirko
  • 72,589
  • 19
  • 149
  • 183
  • It almost work :) when i do a console.log the log from pieces is ["3"] ["4"] I need to remove the "" dots. is it possible to just print the numbers separly without the dots and squere bracket – Dymond Feb 09 '13 at 14:37
  • @Dymond Easiest way would be to change the condition in your `switch` clause to use `+this,value` instead of just `value`. Or you change the case statements to use strings instead of numbers. – Sirko Feb 09 '13 at 14:41