0

what I want to do is the following code

$floorNo = 1; // current floor

if ($floorNo == 1){
  $number1++;
} else if ($floorNo == 2){
  $number2++;
} ...

etc.

Is there a shorter version, something like ($number+$floorNo)++; ?

user3024814
  • 246
  • 3
  • 14

4 Answers4

0

You should use an array for this task:

var $numbers = [1, 2, 3, 4];

var $floorNo = parseInt(prompt("Enter number"), 10);

$numbers[$floorNo - 1]++; // `-1` as the array uses zero-based indexing
Gaurang Tandon
  • 6,504
  • 11
  • 47
  • 84
0

Generally speaking, whenever you have var1, var2, var3, etc. you should probably be using an array instead. For example:

$numbers = [0, 0, 0, 0];  // initialize your numbers

...    

$numbers[$floorNo - 1]++; // increment the number at the given 'floorNo'

Also note that arrays indexes typically start at zero.

p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
0

You could use an array:

var arr = [1, 2, 3];
var floorNo = 1;
arr[floorNo]++; // = [1, 3, 3]

If floorNo is entered by the user, you can use the modulo operator to ensure it's valid:

arr[floorNo % arr.length]++; // = [1, 3, 3]
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
0

You can use eval:

var $floorNo = 1,
    $number1 = 5;

try {
    eval('var $nValue = $number' + $floorNo.toString() + '++;');
    console.log(eval('$number' + $floorNo.toString()));
}
catch(e) {}

Be carefull. Because variables $number1..N must be defined before using eval.