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)++;
?
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)++;
?
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
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.
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]
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.