1

When i try to write a function result to an array tmp, with specified index, the whole array changes to a number.

I tried running the function hex2dec alone, which works like intended and i tried writing a constant to it, which works too. But when i replaced the constant with the function result, the array became 15. (depends on function input)

function clrData(data) {
  data = data.split("");
  tmp = [0, 0, 0];
  tmp[0] = hex2dec(data[0] + data[1]);
  tmp[1] = hex2dec(data[2] + data[3]);
  tmp[2] = hex2dec(data[4] + data[5]);

  return tmp;
}

clrData("FFFFFF") should result in [255, 255, 255] but results in 15

function clrData(data) {
  data = data.split("");
  tmp = [0, 0, 0];
  tmp[0] = hex2dec(data[0] + data[1]);
  tmp[1] = hex2dec(data[2] + data[3]);
  tmp[2] = hex2dec(data[4] + data[5]);

  return tmp;
}

function plc(num) {
  plc = 0;
  
  while (num > 0) {
    num /= 10;
    plc++;
    num = Math.floor(num);
  }
  
  return plc;
}

function hex2dec(num) {
  num = num.toString();
  numArr = num.split("");
  
  num2 = 0;
  for (i=0; i<numArr.length; i++) {
    if (numArr[i] == "0" || numArr[i] == "1" || numArr[i] == "2" || numArr[i] == "3" || numArr[i] == "4" || numArr[i] == "5" || numArr[i] == "6" || numArr[i] == "7" || numArr[i] == "8" || numArr[i] == "9") {
      tmp = Number(numArr[i]);
    } else {
      switch (numArr[i]) {
        case "a":
        case "A":
          tmp = 10;
          break;
        case "b":
        case "B":
          tmp = 11;
          break;
        case "c":
        case "C":
          tmp = 12;
          break;
        case "d":
        case "D":
          tmp = 13;
          break;
        case "e":
        case "E":
          tmp = 14;
          break;
        case "f":
        case "F":
          tmp = 15;
          break;
        default:
          tmp = 0;
      }
    }

    num2 += Math.pow(16, (numArr.length-1) - i) * tmp;
  }

  return num2;
}
<input id="finput" value="FFFFFF"><button onClick="this.innerHTML=clrData(document.getElementById('finput').value)">Activate!</button>

2

1 Answer 1

1

You could get groups of two characters and map the integer value.

function clrData(data) {
    return data.match(/../g).map(h => parseInt(h, 16));
}

console.log(clrData("FFFFFF"));

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.