-1

My code has this

 if (choice != 'A1' || 'A2' || 'A3' || 'B1' || 'B2' || 'B3' || 'C1' || 'C2' || 'C3'){//dosomethingrecursive}

Whenever I choose say, 'A1', it acts as if that is choice is not = to it. which as I understand is wrong, or am I missing something?

Bartholomew
  • 9
  • 1
  • 1
  • 5

3 Answers3

1

In JavaScript and in all programming languages I know, boolean logic operators don't combine in that way, they follow a fixed bool OPERATOR bool schema.

This means that your series of parenthesised || is first incrementally converted to one single value, and that value is then compared with your choice.

The easiest way to achieve the logic you want is by harnessing Array#every to repeat your logical operation on each of your values until the operation fails:

['A1', 'A2', 'A3', 'A4'].every(function(x) { x != choice })

Which translates to: 'choice' must be different from every value in 'array'.

In general everytime you need to repeat something, think about how you could do it with arrays and their iterator methods, it's often the most elegant way.

lleaff
  • 4,249
  • 17
  • 23
1

You can't write it like that. If you don't want to (correctly) chain tests

if (choice != 'A1' && choice != 'A2' && ...

and want something shorter, you could put your values in an array, and test that choice is not an element of the array:

[ 'A1', 'A2', ... ].indexOf( choice ) < 0
Ilya
  • 5,377
  • 2
  • 18
  • 33
0

You can't translate an English sentence into code like this - the meaning of the code is more precise, and in this case different.

Your code calculates

'A1' || 'A2' || 'A3' || 'B1' || 'B2' || 'B3' || 'C1' || 'C2' || 'C3'

and then compares the result to choice. This is not what you want.

You have to do the comparisons individually, e.g.

if (choice != 'A1') && (choice != 'A2') && ...
Mark Smith
  • 880
  • 1
  • 8
  • 25
  • 1
    Almost. It's evaluating `choice != 'A1'`, then the rest. Your conclusion is correct though. – Krease Jan 04 '16 at 17:51