Boolean expressions - getting mixed up with AND, OR logical operators and how they work

ε祈祈猫儿з 提交于 2019-12-11 12:50:10

问题


I have to convert a number to comma format. E.g 12345 => 12,345.

I have my solution :

function convert(n) {
  n = n.toString();
  var result = '';
  var count = 0,
  var idx = n.length - 1;

  while (r = n[idx]) {
    count++;
    result = ((count % 3 == 0 && count != n.length) ? ',' : '') + r + result;
    idx--;
  }
  return result;
}

But someone else used :

    result = ((count % 3 != 0 || count == n.length) ? '' : ',') + r + result;

They both work but now I am confused about my own solution and just lost why they both work. Ah not sure if my question is clear.


回答1:


!(x AND y) is equal to !x OR !y

(and you can pull a NOT out of a boolean x by double negation, for example:

x == !!x

so

x AND !y (your original expression) is equivalent to !(!x OR y)

if you remove the negation (!) from the beginning, then you actually get the Negated form and that is why the second and third values of the ternary operator are reversed in your second example.




回答2:


The two expressions are equivalent, the second one is just the negated version of yours. The opposite (more or less) of == is !=, the opposite of && is ||, and the opposite of true is false.

You are placing a comma whenever the count is divisible by 3 and you aren't at the start of the number. They are not placing a comma anytime the count is not divisible by 3 or they are at the start of the number.




回答3:


Assume that, count % 3 = 0 and count > n.length

Now your logic:

((count % 3 == 0 && count != n.length) ? ',' : '')

which means True && True which results in True hence the first condition after ? which is "," is selected.

Someone else logic:

((count % 3 != 0 || count == n.length) ? '' : ',')

which means 'False || False' which results in 'False' hence second condition after ? which is "," is selected.

P.S: Both are using similar logic



来源:https://stackoverflow.com/questions/28824764/boolean-expressions-getting-mixed-up-with-and-or-logical-operators-and-how-th

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!