JavaScript

Type Conversion in Javascript (number, string)

seoca 2020. 9. 15. 16:47

 

Javascript는 type을 쓰지 않으니 원치않는 결과를 가질 때가 있는데 이럴때 아주 간단하게 형변환을 하는 방법이 있다. 

 

number + string type "" 은 number to string type conversion

string * 1 은  string to number conversion

 

 

Example code

let arr = [1, 2, 3];

console.log(typeof arr); //datatype: object
console.log(typeof arr[1]); //datatype: number

let changeToString = (arr + "").split(","); //number + "": changed to string
console.log(changeToString); //['1', '2', '3']
console.log(typeof changeToString); //datatype: object
console.log(typeof changeToString[1]); //datatype: string

let newArr = [];
for(let i = 0; i < changeToString.length; i++){
    let changeToNumber = arr[i] * 1; //arr[i] * 1: converted to number
    newArr.push(changeToNumber);
}
console.log(newArr); // [1, 2, 3]
console.log(typeof newArr[1]); //datatype: number