简体   繁体   English

如何将此三元运算符表达式转换为if / else块?

[英]How to translate this ternary operator expression into if/else blocks?

我很难使用JS三元运算符将该表达式“转换”为if / else语句,这有助于我更好地可视化代码中正在发生的事情。


mouseX = (window.Event) ? e.pageX : event.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft);

It'll be clearer if you indent your original code - changing only whitespace, your original code is: 如果您缩进原始代码,则会更清楚-仅更改空格,原始代码为:

mouseX = (window.Event)
  ? e.pageX
  : event.clientX + (
    document.documentElement.scrollLeft
    ? document.documentElement.scrollLeft
    : document.body.scrollLeft
  );

Translating that, you get: 将其翻译为:

if (window.Event)
  mouseX = e.pageX;
else {
  let add;
  if (document.documentElement.scrollLeft)
    add = document.documentElement.scrollLeft;
  else
    add = document.body.scrollLeft;
  mouseX = event.clientX + add;
}

We can try writing: 我们可以尝试写:

if (window.Event) {
    mouseX = e.pageX;
}
else {
    var scroll;
    if (document.documentElement.scrollLeft) {
        scroll = document.documentElement.scrollLeft;
    }
    else {
        scroll = document.body.scrollLeft;
    }
    mouseX = event.clientX + scroll;
}

I pulled out the nested ternary expression into a variable scroll . 我将嵌套的三元表达式提取到可变scroll This makes it much easier to rewrite the logic. 这使得重写逻辑变得更加容易。

First of all I want to suggest you to use some linting (eslint, jslint, tslint etc) tool and prettier. 首先,我建议您使用一些棉绒(eslint,jslint,tslint等)工具和更漂亮的工具。 To have better code formatting. 以获得更好的代码格式。 It helps in long run. 从长远来看,它会有所帮助。

The other answers are also valid. 其他答案也有效。 But I want to write one. 但是我想写一个。

if (window.Event) {
  mouseX = e.pageX;
} else {
  let scroll;
  if (document.documentElement.scrollLeft) {
    scroll = document.documentElement.scrollLeft;
  } else {
    scroll = document.body.scrollLeft;
  }
  mouseX = event.clientX + scroll;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM