How to make if judgment in js silky smooth

  • 2021-11-29 05:50:36
  • OfStack

Directory preface code implementation Thoughts 1
Thoughts 2
Summary reference document

Preface

For one small demand point in the project, click the button to verify several 10 condition boxes, and judge whether all condition boxes have filled in (selected) data (at least one condition is judged to be true) before executing the corresponding operation

The judged condition box includes an Radio radio box, an Checkbox multi-selection box, an Input input box, an InputNumber counter, an Select selector, an Switch switch, and the like

Element component library used by the project V2.15. 6

Data types and default values for different conditions

Radio radio box string '' Checkbox Multiple Checkbox array [] Input input box string '' InputNumber Counter number 0 Select selector Radio string '' Multiple selection array [] Switch Switch boolean false

Code implementation

Thoughts 1

Directly use if to judge the dry, and then the approximate code is as follows (the variable is an analog variable)


//  The multi-condition judgment begins as follows 

if (obj.radio1 || obj.checkbox1.length > 0 || obj.input1 || obj.inputNumber1 > 0 || obj.select1 || obj.select2.length > 0 || obj.switch1 || obj.radio2 || obj.checkbox2.length > 0 || obj.input2 || obj.inputNumber2 > 0 || obj.select3 || obj.select4.length > 0 || obj.switch2  ...) {
  // do something
} else {
  //  If the conditions are inconsistent, prompt 
  this.$message({
    message: ' Please select a condition and try again ',
    type: 'warning'
  })
  return false
} 

Because there are many semantic characters in the variable name in the actual project scene, if judges that it has written a long string without writing a few, and then it can't be written after writing a few (it feels like writing a lump of shi)

Can it be achieved in a more elegant way?

Thoughts 2

Put these variables into an array, use map to process them into Boolean type, and use includes to judge whether the array contains the specified Boolean value


//  The multi-condition judgment begins as follows 

const arr = [
  obj.radio1,
  obj.checkbox1.length,
  obj.input1,
  obj.inputNumber1,
  obj.select1,
  obj.select2.length,
  obj.switch1,
  obj.radio2,
  obj.checkbox2.length,
  obj.input2,
  obj.inputNumber2,
  obj.select3,
  obj.select4.length,
  obj.switch2 
  ...
]

const arr1 = arr.map(item => Boolean(item))
if (arr1.includes(true)) {
  // do something
} else {
  //  If the conditions are inconsistent, prompt 
  this.$message({
    message: ' Please select a condition and try again ',
    type: 'warning'
  })
  return false
} 

Well, if handles a lot of judgments about whether it is silkier in this way ^-^

Summarize

Reference document

developer. mozilla. org/zh-CN/docs/… developer. mozilla. org/zh-CN/docs/… developer. mozilla. org/zh-CN/docs/…

Related articles: