development

함수가있는 JavaScript 삼항 연산자 예제

big-blog 2020. 9. 2. 20:14
반응형

함수가있는 JavaScript 삼항 연산자 예제


jQuery 1.7.1을 사용하고 있습니다.

간단한 if / else 문을 대체하기 위해 JavaScript 삼항 연산자를 사용하기 시작했습니다. 나는 여러 곳에서 성공적으로 수행했습니다. 다른 일을 성공적으로 만들었을 때 깜짝 놀랐습니다. 확실히 안 되겠다고 생각했지만 어쨌든 시도했습니다.

다음은 원래 진술입니다.

function updateItem() {
    $this = $(this);
    var IsChecked = $this.hasClass("IsChecked");
    if (IsChecked == true){
        removeItem($this);
    } else {
        addItem($this);
    }
}

삼항 연산자를 사용하는 동일한 함수는 다음과 같습니다.

function updateItem() {
    $this = $(this);
    var IsChecked = $this.hasClass("IsChecked");
    (IsChecked == true) ? removeItem($this) : addItem($this);
}

사용되는 모든 예제가 다음과 같은 변수를 설정했기 때문에 놀랐습니다.

x = (1 < 2) ? true : false;

내 질문은 이것이 "정상적인"사용인지 여부이며 대부분의 JavaScript 버전에서 작동합니까? 어디에서 실패할까요? 다른 덜 분명한 용도가 있습니까?

업데이트- "실제 세계"조언에 감사드립니다 !!!

나는 이것을 내 기능으로 사용하고 있습니다.

function updateItem() {
    $this = $(this);
    $this.hasClass("IsChecked") ? removeItem($this) : addItem($this);
}

Heh, 귀하의 질문에 매우 흥미로운 삼항 구문 사용이 있습니다. 마지막이 제일 좋아요 ...

x = (1 < 2) ? true : false;

여기에서 삼항을 사용하는 것은 완전히 불필요합니다.

x = (1 < 2);

마찬가지로 삼항 문의 조건 요소는 항상 부울 값으로 평가되므로 다음과 같이 표현할 수 있습니다.

(IsChecked == true) ? removeItem($this) : addItem($this);

간단히 :

(IsChecked) ? removeItem($this) : addItem($this);

사실, 나는 또한 당신에게 남겨진 IsChecked임시 도 제거 할 것입니다.

($this.hasClass("IsChecked")) ? removeItem($this) : addItem($this);

이것이 허용 가능한 구문인지에 관해서는 확실합니다! 가독성에 영향을주지 않고 4 줄의 코드를 하나로 줄일 수있는 좋은 방법입니다. 내가 당신에게 줄 유일한 조언은 같은 줄에 여러 삼항 문을 중첩하지 않는 것입니다 (그렇게하면 광기입니다!)


삼항 스타일은 일반적으로 공간을 절약하는 데 사용됩니다. 의미 적으로는 동일합니다. 가독성을 희생하고 싶지 않기 때문에 전체 if / then / else 구문을 선호합니다. 저는 구식이고 중괄호를 선호합니다.

전체 if / then / else 형식은 거의 모든 것에 사용됩니다. 각 분기에서 더 큰 코드 블록에 들어가거나 다중 분기 if / else 트리 또는 긴 문자열에 여러 else / if가있는 경우 특히 인기가 있습니다.

삼항 연산자는 간단한 조건을 기반으로 변수에 값을 할당하거나 매우 짧은 결과로 여러 결정을 내릴 때 일반적입니다. 인용 한 예는 실제로 의미가 없습니다. 표현식이 추가 논리없이 두 값 중 하나로 평가되기 때문입니다.

좋은 생각:

this > that ? alert(this) : alert(that);  //nice and short, little loss of meaning

if(expression)  //longer blocks but organized and can be grasped by humans
{
    //35 lines of code here
}
else if (something_else)
{
    //40 more lines here
}
else if (another_one)  /etc, etc
{
    ...

덜 좋다:

this > that ? testFucntion() ? thirdFunction() ? imlost() : whathappuh() : lostinsyntax() : thisisprobablybrokennow() ? //I'm lost in my own (awful) example by now.
//Not complete... or for average humans to read.

if(this != that)  //Ternary would be done by now
{
    x = this;
}
else
}
    x = this + 2;
}

A really basic rule of thumb - can you understand the whole thing as well or better on one line? Ternary is OK. Otherwise expand it.


There is nothing particularly tricky about the example you posted.

In a ternary operator, the first argument (the conditional) is evaluated and if the result is true, the second argument is evaluated and returned, otherwise, the third is evaluated and returned. Each of those arguments can be any valid code block, including function calls.

Think of it this way:

var x = (1 < 2) ? true : false;

Could also be written as:

var x = (1 < 2) ? getTrueValue() : getFalseValue();

This is perfectly valid, and those functions can contain any arbitrary code, whether it is related to returning a value or not. Additionally, the results of the ternary operation don't have to be assigned to anything, just as function results do not have to be assigned to anything:

(1 < 2) ? getTrueValue() : getFalseValue();

Now simply replace those with any arbitrary functions, and you are left with something like your example:

(1 < 2) ? removeItem($this) : addItem($this);

Now your last example really doesn't need a ternary at all, as it can be written like this:

x = (1 < 2);  // x will be set to "true"

If you're going to nest ternary operators, I believe you'd want to do something like this:

   var audience = (countrycode == 'eu') ? 'audienceEU' :
                  (countrycode == 'jp') ? 'audienceJP' :
                  (countrycode == 'cn') ? 'audienceCN' :
                  'audienceUS';

It's a lot more efficient to write/read than:

var audience = 'audienceUS';
if countrycode == 'eu' {
   audience = 'audienceEU';
} else if countrycode == 'jp' {
   audience = 'audienceJP';
} else if countrycode == 'cn' {
   audience = 'audienceCN';
}

As with all good programming, whitespace makes everything nice for people who have to read your code after you're done with the project.


I would also like to add something from me.

Other possible syntax to call functions with the ternary operator, would be:

(condition ? fn1 : fn2)();

It can be handy if you have to pass the same list of parameters to both functions, so you have to write them only once.

(condition ? fn1 : fn2)(arg1, arg2, arg3, arg4, arg5);

You can use the ternary operator even with member function names, which I personally like very much to save space:

$('.some-element')[showThisElement ? 'addClass' : 'removeClass']('visible');

or

$('.some-element')[(showThisElement ? 'add' : 'remove') + 'Class']('visible');

Another example:

var addToEnd = true; //or false
var list = [1,2,3,4];
list[addToEnd ? 'push' : 'unshift'](5);

I know question is already answered.

But let me add one point here. This is not only case of true or false. See below:

var val="Do";

Var c= (val == "Do" || val == "Done")
          ? 7
          : 0

Here if val is Do or Done then c will be 7 else it will be zero. In this case c will be 7.

This is actually another perspective of this operator.

참고URL : https://stackoverflow.com/questions/10323829/javascript-ternary-operator-example-with-functions

반응형