programing tip

Javascript Ternary 연산자를 사용한 연산자 우선 순위

itbloger 2020. 7. 19. 10:41
반응형

Javascript Ternary 연산자를 사용한 연산자 우선 순위


삼항 연산자와 함께이 코드의 첫 번째 부분 (+ =) 주위에 머리를 감쌀 수 없습니다.

h.className += h.className ? ' error' : 'error'

이 코드가 작동한다고 생각하는 방식은 다음과 같습니다.

h.className = h.className + h.className ? ' error' : 'error'

그러나 내 콘솔에 오류가 발생하기 때문에 올바르지 않습니다.

그래서 내 질문은 어떻게이 코드를 올바르게 삽입해야합니까?


h.className = h.className + (h.className ? ' error' : 'error')

운영자가 작업하기를 원 h.className하고 더 구체적으로 설명하십시오.
물론, 어떤 피해도 없어야 h.className += ' error'하지만 그것은 또 다른 문제입니다.

또한 +삼항 연산자보다 우선합니다 : JavaScript Operator Precedence


이런 식으로 생각하십시오 :

<variable> = <expression> ? <true clause> : <false clause>

명령문이 실행되는 방식은 기본적으로 다음과 같습니다.

  1. <expression>true로 평가 됩니까 , 아니면 false로 평가됩니까?
  2. 만약 <expression>평가하여 true로, 다음의 값 <true clause>에 할당은 <variable>, <false clause>무시하고, 다음 명령문이 실행됩니다.
  3. <expression>false로 평가 되면 <true clause>무시되고의 값이 <false clause>에 지정됩니다 <variable>.

이 언어와 다른 언어에서 삼항 연산자로 인식해야 할 중요한 점은 코드에있는 모든 것이 <expression>평가 될 때 부울 결과를 생성해야한다는 것입니다 (true 또는 false).

귀하의 예의 경우, 설명에서 "할당 됨"을 "추가됨"으로 바꾸거나 사용하는 속기 산술과 비슷합니다 (있는 경우).


+=당신이 원하는 것을, 그러나 그것의 오른쪽에서 삼항 성명에서, 경우 검사 h.className가 정의되지 않은 경우 falsey, 그것은 될 것이다. 진실한 경우 (예 : 클래스 이름이 이미 지정된 경우) 공백이있는 오류가 추가됩니다 (예 : 클래스 추가 ). 그렇지 않은 경우 공백없이 추가됩니다.

제안한대로 코드를 다시 작성할 수 있지만 h.className삼항 연산자에서 실제 값을 사용하는 대신 진실성 비교에 사용 하도록 지정해야 하므로 값을 연결하지 않아도됩니다. 삼항 작업과 동시에 :

h.className = h.className + (h.className ? ' error' : 'error');

=운전자 의 오른쪽 은 왼쪽에서 오른쪽으로 평가됩니다. 그래서,

g.className = h.className + h.className ? ' error' : 'error';`

에 해당

h.className = (h.className + h.className) ? ' error' : 'error';

동등하다

h.className += h.className ? ' error' : 'error';

삼항 진술을 괄호로 분리해야합니다.

h.className = h.className + (h.className ? ' error' : 'error');

if (h.className) {
    h.className = h.className + ' error';
} else {
    h.className = h.className + 'error';
}

다음과 같아야합니다.

h.className += h.className ? ' error' : 'error';

나는 이것이 매우 오래된 질문이라는 것을 알고 있지만, 답변이 모두 불완전한 것처럼 100 % 만족하지는 않습니다. 그래서 우리는 첫번째 교장으로부터 다시갑니다 :

사용자의 전반적인 목표 :

코드 요약 : " error문자열에 클래스 이름이 이미있는 경우 클래스 이름을 문자열 에 추가하고 선택적으로 선행 공백 을 추가하고 싶습니다 ."

가장 간단한 솔루션

Kobi가 5 년 전에 지적한 것처럼 클래스 이름에 선행 공백이 있으면 알려진 브라우저에 아무런 문제가 발생하지 않으므로 가장 짧은 올바른 해결책은 실제로 다음과 같습니다.

h.className += ' error';

즉, 있었어야 실제 답변을 받는 실제 문제 .


그럴 수도 있겠지만, 질문은 ...

1) 왜 이것이 효과가 있었습니까?

h.className += h.className ? ' error' : 'error'

조건부 / 삼항 연산자는 if 문처럼 작동 하여 변수의 경로 true결과를 할당합니다 false.

따라서 코드는 다음과 같이 간단하게 평가되기 때문에 작동했습니다.

if (h.className IS NOT null AND IS NOT undefined AND IS NOT '') 
    h.className += ' error'
else
    h.className += 'error'

2) 왜 이것이 깨졌습니까?

h.className = h.className + h.className ? ' error' : 'error'

"내 콘솔에 [n] 오류가 발생했습니다"라는 질문에 코드 가 작동하지 않는다고 오해 할 수 있습니다 . 실제로 다음 코드는 오류 없이 실행 되지만 문자열 비어 있지 않으면 단순히 'error'를 반환 하고 문자열 비어 있으면 요구 사항을 충족하지 않으면 'error'를 반환합니다 .

이 코드는 항상 다음 의사 코드 로만 평가 ' error'되거나 포함 된 문자열을 'error'생성합니다.

if ((h.className + h.className) IS NOT null AND IS NOT undefined AND IS NOT '')
    h.className = ' error'
else
    h.className = 'error'

The reason for this is that the addition operator (+ to the common folk) has higher "precedence" (6) than the conditional/ternary operator (15). I know the numbers appear backwards

Precedence simply means that each type of operator in a language is evaluated in a particular predefined order (and not just left-to-right).

Reference: Javascript Operator Precedence

How to change the order of evaluation:

Now we know why it fails, you need to know how to make it work.

Some other answers talk about changing the precedence, but you can't. Precedence is hard-wired into the language. That is just a fixed set of rules... However, you can change the order of evaluation...

The tool in our toolbox that can change the order of evaluation is the grouping operator (aka brackets). It does this by ensuring the expressions in the brackets are evaluated before operations outside the brackets. That's all they do, but that's enough.

Brackets work simply because they (grouping operators) have higher precedence than all other operators ("there is now a level 0").

By simply adding brackets you change the order of evaluation to ensure the conditional test is performed first, before the simple string concatenation:

h.className = h.className + (h.className ? ' error' : 'error')

I will now leave this answer to rust unseen among the others :)


I would like to pick explanation of wayne :

<variable> = <expression> ? <true clause> : <false clause>

Lets consider both the cases:

case 1:
h.className += h.className ? 'true' : 'false'     
  • assignment operator works fine and value gets appended
  • when runs for the first time, o/p: false
  • 2nd time. o/p: falsetrue -- values keeps appending

case2: h.className = h.className + h.className ? 'true' : 'false'

  • the result is not same as case 1
  • when runs for the first time, o/p: false
  • 2nd time. o/p: false -- values doesn't keep appending

explanation

In the above code, case 1 works fine

whereas case2:

h.className = h.className + h.className ? 'true' : 'false'
is executed as 
 h.className = (h.className + h.className) ? 'true' : 'false'

h.className + h.className => considered as expression for ternary operator as ternary operator is given higher precedence. so, always the result of the ternary expression is just assigned

You need to define the precedence by using brackets

You need to define the order of evaluation to be considered with the help of brackets for case 2 to work as case 1

h.className = h.className + (h.className ? ' error' : 'error') 

참고URL : https://stackoverflow.com/questions/1788917/operator-precedence-with-javascript-ternary-operator

반응형