0

Sorry for the strange title, it woudn't let me post the question otherwise. Essentially, I would like to update the count of a variable that is chosen depending on the function input. Here is a simplified version. In my code I have around 30 count variables. The countOne function input would be either 1,2 or 3 and would thus update the relevant count1,count2, or count3 depending on the input.

let count1 = 0;
let count2 = 0;
let count3= 0;

function countNumber(countOne, sum) {
    count[countOne] = count[countOne] + sum;

}
  • so you want to call the function like this countNumber("count1", 123)? – Alex - Tin Le Mar 11 '20 at 21:09
  • The function would be called countNumber(1,20) Then the count1 variable that was declared previously would = 20. If the function was again called countNumber(1,5), the count1 variable would now = 25. If countNumber(2,5) was called, the count2 variable would now = 5. – pineappleman92836 Mar 11 '20 at 21:11

1 Answers1

0

The trick is to access property by name. But you need to put your count inside an object.

let data = {
  count1: 0,
  count2: 0,
  count3: 0
};

function countNumber(countOne, sum) {
    data["count" + countOne] += sum;
    alert(`count1 = ${data.count1} --- count2 = ${data.count2} --- count3 = ${data.count3}`);
}

countNumber(1, 20);
countNumber(1, 5);
countNumber(2, 10);
Alex - Tin Le
  • 1,982
  • 1
  • 6
  • 11