简体   繁体   English

javascript if..else 语句到 ? :

[英]javascript if..else statement to ? :

newbie here.新手在这里。 Thanks for your helps.感谢您的帮助。

I'm wondering can I change if ...else ... to ?我想知道我可以改变 if ... else ... 吗? : statement in following codes: : 以下代码中的语句:

https://codepen.io/lgtits/pen/MWoqPBX?editors=1010 https://codepen.io/lgtits/pen/MWoqPBX?editors=1010

list.addEventListener('click', function (event) {
  let target = event.target
  if (target.classList.contains('delete')) {
    let parentElement = target.parentElement
    parentElement.remove()
  } else if (target.tagName === 'LABEL') { 
    target.classList.toggle('checked')
  }
})

just like this:像这样:

let a = 1

let b = 2

if(a>b) {
  console.log('bigger')
} else if (a === b) {
  console.log('equal')
} else {
  console.log('smaller')
}

a > b ? console.log('bigger') : 
      a === b ? console.log('equal') :
      console.log('smaller')

You could change the first block if...else if to the following:您可以将第一个块if...else if更改为以下内容:

list.addEventListener("click", function (event) {
  let target = event.target;
  // set this ahead of time if needed
  let parentElement = target.parentElement;
  target.classList.contains("delete")
    ? parentElement.remove()
    : target.tagName === "LABEL"
      ? target.classList.toggle("checked")
      : void 0;
});

It can tend to get clunky if you have too many different things to check for, but it's doable if you're only doing one operation each in if and else blocks.如果您有太多不同的东西要检查,它可能会变得笨拙,但如果您只在ifelse块中执行一项操作, if它是可行的。 Just remember to make sure it is readable.只要记住确保它是可读的。

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

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