Aesthetic Cookie Aesthetic Cookie - 6 months ago 12
Javascript Question

How can I slice a number into smaller digits to fit my array

I am making a counter which will show the sum of dice rolled. At the moment if i go over 9 it turns into zero. I need to slice up the number of zeroValue into one digit long sections. so 123 becomes 1 23, 1 2 3, 12 3. So that it fits into my array. I tried something like this:

function diceResult(){

var whichNumber = 123; // this number will change, depending on sum of dice rolled

var getTextNumber = new Array (9)
getTextNumber[0] = "zero";
getTextNumber[1] = "one";
getTextNumber[2] = "two";
getTextNumber[3] = "three";
getTextNumber[4] = "four";
getTextNumber[5] = "five";
getTextNumber[6] = "six";
getTextNumber[7] = "seven";
getTextNumber[8] = "eight";
getTextNumber[9] = "nine";

var zeroValue = getTextNumber[whichNumber];

var getZero = diceToolbarCounterWrapper.getElementsByTagName("li");

getZero[2].className = zeroValue.slice(2, -0; /* <------ I tried this */
getZero[1].className = zeroValue.slice(1, -1);
getZero[0].className = zeroValue.slice(0, -1);

};


Unfortunately this doesn't work. Another problem with this is that if the number is under 3 digits long it removes too many digits. This is what I want to happen if the sum of dice rolled is 123:

getZero[2].className = "one";
getZero[1].className = "two";
getZero[0].className = "three";


How can I achieve this? Please add code to your answer as I am new to javaScript.

Dan Dan
Answer

As it stands zeroValue will be undefined whenever it is over 9. This is because

var getTextNumber = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"] and getTextNumber[123] === undefined // true.

You would need to split whichNumber before you do the lookup. This is going to get very longhand, e.g. var whichNumber1 = whichNumber.toString().slice(0,1) and so on. Rather than go down that road, I'd recommend using split:

function diceResult(){

  var whichNumber = getSumDiceValue(); //sum of dice rolled.

  var getTextNumber = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]

  var splitNumber = whichNumber.toString().split(""); // ["1", "2", "3"]

  var getZero = diceToolbarCounterWrapper.getElementsByTagName("li");

  getZero[0].className = getTextNumber[splitNumber[0]];
  if (splitNumber.length > 1) {
    getZero[1].className = getTextNumber[splitNumber[1]]
  } else {
    getZero[1].className = "";
  }
  if (splitNumber.length > 2) {
    getZero[2].className = getTextNumber[splitNumber[2]];
  } else {
    getZero[2].className = "";
  }
};

Edit: to solve the backwards positioning problem you could rewrite this as:

for (i = splitNumber.length - 1; i >= 0; i--) {      
  getZero[2 - i].className = getTextNumber[splitNumber[i]];
}

if (splitNumber.length === 1) {
  getZero[0].className = "";
  getZero[1].className = "";
}

if (splitNumber.length === 2) {
  getZero[0].className = "";
}
Comments