JavaScript: Can one use "Object.prototype.toString.call(obj)" for data-type detection? -
if 1 calls tostring-method of object call (for changing context) string returned. string contains data-type of value given call.
var obj = {}; var field = []; var str = 'abc'; var num = 3; var reg = /.*/; var bool = true; var notanumber = nan; var undef = undefined; console.log(object.prototype.tostring.call(obj)); // [object object] console.log(object.prototype.tostring.call(field)); // [object array] console.log(object.prototype.tostring.call(str)); // [object string] console.log(object.prototype.tostring.call(num)); // [object number] console.log(object.prototype.tostring.call(reg)); // [object regexp] console.log(object.prototype.tostring.call(bool)); // [object boolean] console.log(object.prototype.tostring.call(notanumber)); // [object number] console.log(object.prototype.tostring.call(undefined)); // [object undefined]
what can tinkering: beside usual javascript weirdness (nan number) seems work fine.
now ask myself:
if make function .split(/\s/) etc., returning data-type string use type-detection.
but makes me distrustful:
i have never seen programmers use object.prototype.tostring.call-construct way. use typeof or methods ...
so question is:
would function described above work expected?
or fail because of different javascript implementations in browser? or fail because of other reason?
according specifications @ mdn, object.prototype.tostring
supported on browsers, should work consistently.
i point out detecting difference between array
, object
differentiate results using typeof
:
edit 1
and reg
variable detects object
.
var obj = {}; var field = []; var str = 'abc'; var num = 3; var reg = /.*/; var bool = true; var notanumber = nan; var undef = undefined; console.log(typeof obj); // object console.log(typeof field); // object console.log(typeof str); // string console.log(typeof num); // number console.log(typeof reg); // object console.log(typeof bool); // boolean console.log(typeof notanumber); // number console.log(typeof undefined); // undefined //data original post: console.log(object.prototype.tostring.call(obj)); // [object object] console.log(object.prototype.tostring.call(field)); // [object array] console.log(object.prototype.tostring.call(str)); // [object string] console.log(object.prototype.tostring.call(num)); // [object number] console.log(object.prototype.tostring.call(reg)); // [object regexp] console.log(object.prototype.tostring.call(bool)); // [object boolean] console.log(object.prototype.tostring.call(notanumber)); // [object number] console.log(object.prototype.tostring.call(undefined)); // [object undefined]
Comments
Post a Comment