Strong Root

typeof 는 Array, Date, Object 모두 "object" 를 리턴하여 구분이 불가능하므로, constructor 를 이용하여 해결한다.




1
2
3
function isArray(myArray) {
    return myArray.constructor.toString().indexOf("Array"> -1;
}
cs




1
2
3
function isDate(myDate) {
    return myDate.constructor.toString().indexOf("Date"> -1;
}
cs






출처 : http://www.w3schools.com/js/js_type_conversion.asp

1
2
3
4
5
6
age = Number(age);
if (isNaN(age)) {
    voteable = "Error in input";
else {
    voteable = (age < 18) ? "Too young" : "Old enough";
}
cs






출처 : http://www.w3schools.com/js/js_comparisons.asp

"" (empty string) 의 Boolean 값은 false 다.

1
2
var x = "";
Boolean(x);       // returns false
cs




undefined 의 Boolean 값은 false 다.

1
2
var x;
Boolean(x);       // returns false
cs




null 의 Boolean 값은 false 다.

1
2
var x = null;
Boolean(x);       // returns false
cs






그렇다면 String값의 이상유무를 확인할 때, 아래와 같이 써주면 끝?

1
2
3
4
5
6
if (x) {
    // valid
}
else {
    // invalid
}
cs




틀렸다면 이유를 알려주시면 감사합니다.






출처 : http://www.w3schools.com/js/js_booleans.asp + 내추측

1
2
3
4
5
var myNumber = 128;
 
myNumber.toString(16);    // returns 80
myNumber.toString(8);    // returns 200
myNumber.toString(2);    // returns 10000000
cs






출처 : http://www.w3schools.com/js/js_numbers.asp

소수 연산(Floating point arithmetic)은 때때로 정확하지 않다.


1
2
3
var x = 0.2 + 0.1;
 
alert(x);    // alert 0.30000000000000004
cs






위 문제를 해결하기 위해 정수형 연산으로 바꿔 계산한다.


1
2
3
var x = (0.2 * 10 + 0.1 * 10/ 10;
 
alert(x);    // alert 0.3
cs






출처 : http://www.w3schools.com/js/js_numbers.asp

1
2
3
4
5
{
    var age = 20;
}
 
alert(age);    // alert 20
cs


코드 블럭을 무시하고 변수가 인식된다.


결론 :

JavaScript는 블럭 스코프를 지원하지 않는다.

(JavaScript does NOT support Block Scope.)






출처 : My brain and fingers

1
2
3
4
5
6
7
8
9
10
11
12
13
var age = 20;
 
function increaseAge(amount) {
    age += amount;
}
 
function increaseAge() {
    age++;
}
 
increaseAge(10);
 
alert(age);    // alert 21
cs


에러는 안나지만, 앞의 함수를 무시하고 마지막에 쓴 함수만 작동한다.


결론 :

JavaScript는 오버로딩을 지원하지 않는다.

(JavaScript does NOT support Method Overloading.)






출처 : My brain and fingers

Empty value

var car = "";                // The value is "", the typeof is string
cs




Null vs Undefined

var person = null;           // Value is null, but type is still an object
var person = undefined;     // Value is undefined, type is undefined
 
typeof undefined             // undefined
typeof null                  // object
null === undefined           // false
null == undefined            // true
cs






출처 : http://www.w3schools.com/js/js_datatypes.asp