Javascript: Tìm hiểu về type và cách kiểm tra type đúng

Trong Javascript định nghĩa 7 data type như sau:
6 primitive types: Boolean, Null, Undefined, Number, String, Symbol
Object

Mọi thứ trong Javascript đều là Object. Boolean, Null, Undefined, Number, String, Symbol đều là Object? Bạn thấy có lạ không? Ta có thể kiểm tra type của từng thằng như sau nhé 🙂

typeof []; // object, Array là một Object
typeof {}; // object
typeof ''; // string, String không phải là Object? Không.
//Nó là object. Hãy xem giải thích tiếp theo tại sao String là Object nhé
typeof new Date() // object
typeof 1; // number, tương tự string
typeof function () {}; // function
typeof /test/i; // object
typeof true; // boolean, tương tụ như string
typeof null; // object
typeof undefined; // undefined, tương tự string

Ta thấy kết quả lạ bởi vì typeof kiểm tra không như ta hiểu. Nhưng ta sẽ có cách kiểm tra type khác.

Object.prototype.toString.call();

Hãy nhìn xem nhé:

Object.prototype.toString.call([]); // [object Array]
Object.prototype.toString.call({}); // [object Object]
Object.prototype.toString.call(''); // [object String]
Object.prototype.toString.call(new Date()); // [object Date]
Object.prototype.toString.call(1); // [object Number]
Object.prototype.toString.call(function () {}); // [object Function]
Object.prototype.toString.call(/test/i); // [object RegExp]
Object.prototype.toString.call(true); // [object Boolean]
Object.prototype.toString.call(null); // [object Null]
Object.prototype.toString.call(); // [object Undefined]

See? Tất cả đều là object, chỉ có khác là type mà thôi. Is that make sense?
Theo tôi dùng cách này check type khá hợp lý. Bạn có thể dùng thư viện lodash hoặc Axis.

axis.isArray([]); // true
axis.isObject({}); // true
axis.isString(''); // true
axis.isDate(new Date()); // true
axis.isRegExp(/test/i); // true
axis.isFunction(function () {}); // true
axis.isBoolean(true); // true
axis.isNumber(1); // true
axis.isNull(null); // true
axis.isUndefined(); // true

Sử dụng cách trên đây ta có thể biết rõ type là gì: isArray, isObject, isString, …
Cool 🙂

One Comment

Leave a Reply

Your email address will not be published. Required fields are marked *