program story

Javascript에서 Type Coercion은 정확히 무엇입니까?

inputbox 2020. 8. 9. 10:25
반응형

Javascript에서 Type Coercion은 정확히 무엇입니까?


Javascript에서 유형 강제는 정확히 무엇입니까?

예를 들어, ==대신 ===?


유형 강제는 연산자의 피연산자가 다른 유형일 때 그 중 하나가 다른 피연산자의 유형과 "동등한"값으로 변환됨을 의미합니다. 예를 들어 다음과 같은 경우 :

boolean == integer

부울 피연산자는 정수로 변환 false됩니다. 0, true1이됩니다. 그런 다음 두 값이 비교됩니다.

그러나 비 변환 비교 연산자를 사용하면 ===이러한 변환이 발생하지 않습니다. 피연산자가 다른 유형이면이 연산자는을 반환 false하고 동일한 유형일 때만 값을 비교합니다.


유형 강제의 일반적인 개념을 이해하는 데 도움이 될 유형 시스템에 대한 간략한 소개부터 시작하겠습니다.

언어 유형 시스템은 해당 언어에 존재하는 데이터 유형과 다른 연산자를 사용하여 결합 할 수있는 방법을 알려주는 규칙을 정의합니다. 예를 들어, 이러한 규칙 중 하나는 더하기 (+) 연산자가 숫자에만 적용되도록 지정할 수 있습니다. 이러한 규칙은 주로 발에 총을 쏘는 것을 방지하기 위해 존재합니다. 하지만 프로그래머가 프로그램에서 그 규칙을 어기면 어떻게 될까요? 언어가 해당 표현이 의미가 없다고 생각하더라도 프로그래머가 프로그램을 입력 {} + {}하거나 입력하는 것을 방해하는 “hello” + 5것은 없습니다.

이러한 상황에서 궁극적으로 일어나는 일은 언어가 유형 규칙에 대해 얼마나 엄격한 지에 따라 다릅니다.

언어 유형 시스템은 종종 규칙을 위반하는 두 가지 입장 중 하나를 보유합니다.

  1. "이봐, 멋지지 않아!"라고 말합니다. 즉시 프로그램을 중단하십시오.
  2. “{}로는 아무것도 할 수 없지만 숫자로는 할 수 있어요”라고 말하고 {}를 숫자로 변환 해 봅니다.

규칙에 대해 첫 번째 위치를 차지하는 유형 시스템을 사용하는 언어를 구어 적으로 "강력한 유형"언어라고합니다. 그들은 당신이 그 규칙을 어 기지 못하게하는 것에 대해 엄격합니다. 두 번째 접근 방식 (예 : JavaScript)을 사용하는 언어를 "약한 유형"또는 "느슨한 유형"언어라고합니다. 물론 규칙을 어길 수는 있지만 규칙을 준수하기 위해 프로그램에서 설명한 데이터 유형을 강제로 변환 할 때 놀라지 마십시오. 그 행동은… (드럼 롤) ... 유형 강제 라고 알려져 있습니다.

이제 JavaScript의 몇 가지 예를 살펴 보겠습니다. 먼저 유형 강제로 이어지지 않는 표현식부터 시작하겠습니다.

5 + 5

완벽하게 유효한 두 숫자에 + 연산자를 사용합니다. 이 프로그램은 +를 "더하기"를 의미하는 것으로 취급하고 행복하게 두 숫자를 더합니다. 변환이 필요하지 않습니다.

하지만…

[] + 5

어 오. JavaScript에서 +두 개의 숫자를 추가하거나 두 개의 문자열을 연결하는 것을 의미 할 수 있습니다. 이 경우 두 개의 숫자도없고 두 개의 문자열도 없습니다. 우리는 오직 하나의 숫자와 객체를 가지고 있습니다. JavaScript의 유형 규칙에 따르면 이것은 논리적으로 의미가 없습니다. 그것은 당신이 규칙을 어기는 것을 용서하기 때문에, 충돌하는 대신 어쨌든 그것을 이해하려고 노력합니다. 그렇다면 JavaScript는 무엇을합니까? 음, 문자열을 연결하는 방법을 알고 있으므로 []와 5를 모두 문자열로 변환하고 결과는 문자열 값 "5"입니다.

비교 연산자 ==의 거래는 무엇입니까 ===? 두 개의 비교 연산자가있는 이유는 무엇입니까?

==JavaScript의 유형 변환 동작에 영향을받지 않습니다. 5 == “5”will 과 같은 표현식 은 JavaScript가 동일한 유형의 데이터를 비교하도록 이들 중 하나를 변환하려고 시도하기 때문에 true 평가됩니다.

대부분의 경우 비교 대상 데이터가 다른 유형인지 알고 싶어서 수행 할 작업을 결정할 수 있기 때문에 바람직하지 않습니다. 그것이 ===연산자가 들어오는 입니다.를 사용하면 ===유형 변환이 발생하지 않습니다. 따라서 표현식 5 === “5”은 거짓으로 평가됩니다.


Python에서 문자열과 정수를 추가하려고하면 오류가 발생합니다.

>>> "hi" + 10
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int' objects

그러나 JavaScript에서는 그렇지 않습니다. 10문자열로 변환됩니다 :

> "hi" + 10
"hi10"

"유형 강제"는 위의 이름에 대한 멋진 잘못된 이름입니다. 실제로 어떤 언어도 Java 나 C 또는 정적 유형 시스템을 사용하는 다른 언어의 의미에서 "유형"이 없습니다. 언어가 다양한 비 정적 유형 값 간의 상호 작용을 처리하는 방법은 선택과 관례의 문제입니다.


다음 예제로 유형 강제를 설명하겠습니다.

Type Coercion은 Javascript가 자동으로 (즉석에서) 변수를 한 데이터 유형에서 다른 데이터 유형으로 변환 함을 의미합니다.

예 : 123 + "4"일반적으로 오류가 발생하지만 유형 강제로 인해 Javascript 1234에서는 문자열이 발생합니다.

if(23 == "23"){
    console.log(" this line is inside the loop and is executed ");
}

In the above code, because of type coercion - JavaScript thinks 23 (number) and "23" (string) are the same thing. this makes the condition true and prints the console.log

In the other case

if(23 === "23"){
   console.log(" this line is inside the loop and is NOT executed");
}

In === case Javascript doesn't do Type Coercion, and since 23 is a number and "23" is String and because of === these two datatypes are different and that leads to the false in condition. It does not print the console.log

In simple words

In this case = it is an assignment operator - which assigns values such as var a = 3;, etc

(below operators are for comparison)

In this case == Javascript converts/coerces the datatype to another and then compares it.

In this case === Javascript doesn't convert/coerces the datatype

In order to avoid bugs and for debugging purposes === is mostly used

Please let me know the accuracy of the above information.


a == b means javascript will evaluate a against b based on if the values can be evaluated equally. For example, false == 0 will evaluate true because 0 is also the value of Boolean false. However, false === 0 will evaluate false because strictly comparing, 0 is not the same physical value as false. Another example is false == '' So basically loose comparison vs. strict comparison, because javascript is a loosely typed language. That is to say, javascript will attempt to convert the variable based on the context of the code, and this has the effect of making things equal if they are not strictly compared. php also has this behavior.


var str = 'dude';
console.log(typeof str); // "string"
console.log(!str); // false
console.log(typeof !str); // "boolean"

Example of a variable which is initially declared as a string being coerced into boolean value with the ! operator


What is coercion:

Type coercion in javascript occurs when the Javascript engine has to perform a certain operation for which it needs data to be in a certain type. When the engine encounters data in a certain type that is not applicable for the operation it then coerces the data into a certain type. This is needed because variables in javascript are dynamically typed, which means that a given variable can be assigned a value of any type.

Example:


if(1){
  // 1 gets coerced to true
}


if(4 > '3') {
  // 3 gets coerced into a number
}


44 == "44"  // true, the string 44 gets converted to a nr

Boolean coercion:

In javascript coercion, all values are converted to true except for the following values which are coerced to false:

console.log(!!"");         // false
console.log(!!0);          // false
console.log(!!null);       // false
console.log(!!undefined);  // false
console.log(!!NaN);        // false
console.log(!!false);      // false

Also notice that in the above example that the double ! operator is used. The ! mark operator coerces a value into a boolean with the opposite value. We can use this operator twice to convert any value into a boolean.


If data type is not equal with each other then Coercion Happen. like 3 == "3" or boolen == integer

참고URL : https://stackoverflow.com/questions/19915688/what-exactly-is-type-coercion-in-javascript

반응형