Meaning of code with a lot of '?' and ':' in argument parts

Asked 2 years ago, Updated 2 years ago, 110 views

I'm a beginner at jquery.

I'm very sorry, but could you tell me the meaning below?

fields.eq(index+(event.shiftKey?(index>0?-1:0):(index<total?+1:total)) .focus();

javascript jquery

2022-09-30 21:14

1 Answers

As I wrote in the question comment, I don't have enough information, so I can't help but guess the details, but the code you gave me is very difficult to understand even if I'm not a beginner, so I'd like to try to explain it a little.

fields—jQuery object that bundles multiple input elements
index—Index (0~) number of the input elements above that are currently in focus. total—Number of all input elements above
That's what I'm going to say.

Nesting a three-term operator (?:) and using a three-term operator inside a long expression are two major techniques to make the code difficult to read, but both are used, so it is quite difficult to read.If you replace that part with an if statement, it will be a little longer, but it will look like this

var newFocusedIndex;
            if(event.shiftKey){
                // If the shift key is pressed at the same time, click here
                if(index>0){
                    // Decrease index by 1 if it's OK
                    newFocusedIndex=index+(-1);
                } else{
                    // If it's not okay, just do it
                    newFocusedIndex=index+(0);
                }
            } else{
                Error in if(index<total) {//`index<total-1`?
                    // If it's okay to increase index by 1(?), increase it by 1
                    newFocusedIndex=index+(+1);
                } else{
                    // If it's not okay, what do you want to do???
                    Don't you really want newFocusedIndex=index+(0); // to be the same as when reducing? 
                }
            }
            Focus on the newFocusedIndex element in // fields
            fields.eq(newFocusedIndex).focus();

(The part enclosed in redundant brackets is the original code and is calculated by nesting the three-term operator.)
It's a code that says.If you modify a part of the code and run it as "What to do when the tab key is pressed," you can control the focus movement of the tab by yourself, but because of the ?, you have no idea what you want to do.

So I ended up with "I don't know what I want to do at all," but it's going to make me think about whether I should write a code like 'I can write this code in one line, I'm amazing' or a code that's easy for others to understand.


2022-09-30 21:14

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.