判断是不是对象

小鱼儿 2022-05-11 08:56 350阅读 0赞

判断是不是对象 typeof不准确

  1. //方法一
  2. var arr = [];
  3. var obj = new Object();
  4. typeof obj === 'object' //true
  5. //方法二
  6. arr instanceof Object //true
  7. arr instanceof Array //true
  8. 方法一二都不严谨
  9. //方法三
  10. var s = 'a string';
  11. var arr = [];
  12. var obj = new Object();
  13. if (typeof s == 'string') {
  14. console.log("typeof s=='string' true"); //true
  15. }
  16. //打开浏览器的控制台,可以看到此代码的输出
  17. console.log('s.constructor==String :' + (s.constructor == String));
  18. console.log('arr.constructor==Array :' + (arr.constructor == Array));
  19. console.log('obj.constructor==Object :' + (obj.constructor == Object));
  20. //复杂类型的对象,判断其类型
  21. function User(name, age) {
  22. this.name = name;
  23. this.age = age;
  24. }
  25. var u = new User();
  26. console.log('typeof u :' + typeof u);
  27. //输出object //显然,使用typeof判断复杂类型的对象,就失效了,但使用constructor就可以获取其真实类型
  28. console.log('u.constructor.name :' + u.constructor.name);
  29. //方法四
  30. function isArray(obj) {
  31. return Object.prototype.toString.call(obj) === '[object Array]';
  32. }
  33. function isObject(obj) {
  34. return Object.prototype.toString.call(obj) === '[object Object]';
  35. }

发表评论

表情:
评论列表 (有 0 条评论,350人围观)

还没有评论,来说两句吧...

相关阅读