π»νλ³ν, Castingπ»
νλ³ν λ΄μ₯ ν¨μ(Built-in Function)
1. number parseInt(value) : valueλ₯Ό μ μλ‘ λ³ννλ€.
2. number parseFloat(value) : valueλ₯Ό μ€μλ‘ λ³ννλ€.
number parseInt(value)
<script>
var n1 = 3.14;
console.log(parseInt(n1)); //3
n1 = 3.99; //λ°μ¬λ¦Όλμ§ μμ
console.log(parseInt(n1)); //3
</script>
λ³μμ κ°μ μ μνμ¬ μ μλ‘ λ°ννλ€.
<script>
var n2 = '300';
console.log(n2, typeof n2); //string
console.log(parseInt(n2)); //300
console.log(n2, typeof parseInt(n2)); //number
</script>
μ«μλ₯Ό λ¬ΈμνμΌλ‘ ννν λ°μ΄ν°λ μ μλ‘ λ³νμ΄ κ°λ₯νλ€.
<script>
var n3 = 'νκΈΈλ';
console.log(parseInt(n3)); //NaN
</script>
λ¨, λ¬Έμλ°μ΄ν°λ§ μλ κ²½μ° NaN κ°μ λ°ννλ€.
(NaN : Not a Number, μ«μκ° μλλ€)
<script>
var n4 = '100μ ';
console.log(parseInt(n4)); //100
n4 = 'μ€μ½μ΄90';
console.log(parseInt(n4)); //NaN
n4 = '100μ μ΄ μλ 95μ ';
console.log(parseInt(n4)); //100
</script>
μ«μκ° μμ λμ€λ©΄ μμ λμ¨ μ«μλ§ μΈμνμ¬ λ°ννλ€.
<script>
var width = '200px';
console.log(width + 100); //200px100
console.log(parseInt(width)+100); //300
</script>
javascriptμμ css μ‘°μν λ μμ κ°μ΄ μ¬μ©νκΈ°λ νλ€.
number parseFloat(value)
parseInt μ λμΌνλ€.
<script>
var size = '1.5em';
console.log(parseFloat(size)) //1.5
</script>
boolean isNaN(value)
- 'valueκ° μ«μκ° μλλκΉ'λ₯Ό μλ―Ένλ€.
- true : μ«μκ° μλλ€.
- false : μ«μμ΄λ€.
<script>
var age = 20;
console.log(isNaN(age)); //false
age = '20μΈ';
console.log(isNaN(age)); //true
</script>
μ ν¨μ±κ²μ¬ ν λ νΈλ¦¬νλ€.
<script>
age = '20μΈ';
if (isNaN(age)){
console.log('λμ΄κ° μ¬λ°λ₯΄μ§ μμ΅λλ€.');
} else {
console.log('μ¬λ°λ₯Έ λμ΄μ
λλ€.');
}
</script>
'WEB > JavaScript' μΉ΄ν κ³ λ¦¬μ λ€λ₯Έ κΈ
[JavaScript] Date κ°μ²΄ (0) | 2023.10.05 |
---|---|
[JavaScript] λ¬Έμμ΄ ν¨μ (0) | 2023.10.05 |
[JavaScript] λ³μμ μ€μ½ν (0) | 2023.10.05 |
[JavaScript] undefinedμ μ§μ± λΉκ΅ μ°μ°μ(===, !===) (0) | 2023.10.04 |
[JavaScript] function (0) | 2023.10.04 |