Advertisement
Guest User

Untitled

a guest
Nov 23rd, 2017
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.12 KB | None | 0 0
  1. // More exact variable type is possible only by prototype toString method:
  2. var realTypeOf = function (object) {
  3. // typeStr is always in form: '[object MoreSpecificName]'
  4. var typeStr = {}.toString.apply(object);
  5. // let's return only the last part 'MoreSpecificName'
  6. var result = typeStr.substr(8, typeStr.length - 9);
  7. if (result == "Number") {
  8. if (!isFinite(object)) {
  9. result += ".Inifinite";
  10. } else if (isNaN(object)) {
  11. result += ".NaN";
  12. } else if (object.toString.indexOf('.') > -1) { // Math.round(object) !== object
  13. result += ".Float";
  14. } else {
  15. result += ".Int";
  16. }
  17. }
  18. return result;
  19. };
  20.  
  21. // now is returning type much better:
  22. console.log(
  23. realTypeOf({}), // Object
  24. realTypeOf(1), // Number.Int
  25. realTypeOf(.5), // Number.Float
  26. realTypeOf(NaN), // Number.NaN
  27. realTypeOf(Infinity), // Number.Inifinite
  28. realTypeOf(""), // String
  29. realTypeOf(false), // Boolean
  30. realTypeOf([]), // Array
  31. realTypeOf(new Date()), // Date
  32. realTypeOf(null), // Null
  33. realTypeOf(undefined), // Undefined
  34. realTypeOf(function(){})// Function
  35. );
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement