두 문자열 하나로 합치기
두 문자열을 합쳐서 하나의 문자열로 출력하거나 저장하고 싶을때!
+를 이용하면 된다.
let firstName = "code";
let lastName = "kim";
let name = firstName + lastName;
console.log(firstName + lastName) // codekim
console.log(name) // codekim
console.log("문자열"+1); // 문자열1
마지막처럼 문자열에 숫자를 더하면 숫자가 자동 형변환 되어서 문자열로 합쳐진다.
자바스크립트의 형변환
1. 자동 형변환
console.log("5"+3); //53
console.log(5+"3"); //53
// 문자와 숫자를 +하면 숫자가 문자열로 형변환되어 문자열이 합쳐진다.
console.log("5"-3); // 2
console.log(5-"3"); // 2
// -연산을 하면 문자열 형태로 저장되어 있던 숫자를 숫자타입으로 형변환해서 연산을 수행한다.
console.log("문자열"-2); // NaN
// 문자열은 숫자로 변환할 수 없어서 NaN을 반환한다.
숫자가 문자타입으로 저장되어 있는 경우도 자동 형변환으로 숫자로 변환해서 연산을 수행한다.(+연산은 제외)
숫자, 문자열 뿐 아니라 불린, null, undefined타입도 가능하다.
2. 명시적 형변환
자료형을 사용자가 명시적으로 변환하는 것도 가능하다.
let a = "5";
console.log( a + 3 ); // 53
console.log( Number(a) + 3 ); // 8
let y = "5";
console.log(typeof(y)); // string
let x = + y;
console.log(typeof(x)); // number
Number()함수나 +를 이용하면 데이터를 숫자타입으로 변환할 수 있다.
String(), Boolean(), object()로 문자열, 불린, 객체타입으로 변환할 수 있다.
숫자, 문자열 외 다양한 형변환 참고 사이트
https://www.w3schools.com/js/js_type_conversion.asp
JavaScript Type Conversions
W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.
www.w3schools.com
https://www.programiz.com/javascript/type-conversion
JavaScript Type Conversions (with Examples)
In programming, type conversion is the process of converting data of one type to another. For example: converting String data to Number. There are two types of type conversion in JavaScript. Implicit Conversion - automatic type conversion Explicit Conversi
www.programiz.com
'JavaScript' 카테고리의 다른 글
자바스크립트 | 객체 속성 키와 값 배열로 추출하기 Object.keys(), Object.values(), Object.entries() (0) | 2022.06.19 |
---|---|
자바스크립트 | 속성 접근자 .(dot notation), [](bracket notation) (0) | 2022.06.18 |
자바스크립트 NaN (0) | 2022.05.27 |
자바스크립트 null / undefined (0) | 2022.05.26 |
자바스크립트 변수선언 const / let / var (0) | 2022.05.25 |