Preface
A small requirement point in the project, click the button to verify dozens of condition boxes, determine whether all condition boxes have filled in (selected) data (at least one condition is judged to be true) and then perform the corresponding operation
The judged condition box includes Radio radio box, Checkbox multi-check box, Input input box, InputNumber counter, Select selector, Switch switch, etc.
Element component library used by the project V2.15.6
Data types and default values for different conditions
- Radio radio box string ''
- Checkbox Multiple Selection Box array []
- Input input box string ''
- InputNumber Counter number 0
- Select selector
- Single choice string ''
- Multiple choice array []
- Switch switch boolean false
Code implementation
Idea 1
Use if to determine the open-dry, and then the code is roughly as follows (the variable is a simulated variable)
// Multi-condition judgment starts, as follows if (obj.radio1 || obj. > 0 || obj.input1 || obj.inputNumber1 > 0 || obj.select1 || obj. > 0 || obj.switch1 || obj.radio2 || obj. > 0 || obj.input2 || obj.inputNumber2 > 0 || obj.select3 || obj. > 0 || obj.switch2 ...) { // do something } else { // The conditions do not match, prompt this.$message({ message: 'Please select the conditions and try again', type: 'warning' }) return false }
The variable names in the actual project scenario are many semantic characters. If you judge that if you don’t write a few, you write a long string, and then you can’t write it after writing a few (I feel like you’re writing a bunch of shi)
Can it be achieved in a more elegant way?
Idea 2
Put these variables that need to be judged into an array, use map to process them into Boolean type, and use include to determine whether the array contains the specified Boolean value.
// Multi-condition judgment starts, as follows const arr = [ obj.radio1, obj., obj.input1, obj.inputNumber1, obj.select1, obj., obj.switch1, obj.radio2, obj., obj.input2, obj.inputNumber2, obj.select3, obj., obj.switch2 ... ] const arr1 = (item => Boolean(item)) if ((true)) { // do something } else { // The conditions do not match, prompt this.$message({ message: 'Please select the conditions and try again', type: 'warning' }) return false }
OK, if processing a lot of judgments in this way to make it more silky ^-^
Summarize
This is the article about how to make if judgment in js as smooth as silk. For more related content in js, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!
Reference Documents
- /zh-CN/docs/…
- /zh-CN/docs/…
- /zh-CN/docs/…