• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
xwlong
博客园    首页    新随笔    联系   管理    订阅  订阅
typeof操作符,返回数据类型Array.isArray()、Object.prototype.toString.call()

源地址https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/typeof

typeof操作符

 1 // Numbers
 2 typeof 37 === 'number';
 3 typeof 3.14 === 'number';
 4 typeof Math.LN2 === 'number';
 5 typeof Infinity === 'number';
 6 typeof NaN === 'number'; // 尽管NaN是"Not-A-Number"的缩写
 7 typeof Number(1) === 'number'; // 但不要使用这种形式!
 8 
 9 // Strings
10 typeof "" === 'string';
11 typeof "bla" === 'string';
12 typeof (typeof 1) === 'string'; // typeof总是返回一个字符串
13 typeof String("abc") === 'string'; // 但不要使用这种形式!
14 
15 // Booleans
16 typeof true === 'boolean';
17 typeof false === 'boolean';
18 typeof Boolean(true) === 'boolean'; // 但不要使用这种形式!
19 
20 // Symbols
21 typeof Symbol() === 'symbol';
22 typeof Symbol('foo') === 'symbol';
23 typeof Symbol.iterator === 'symbol';
24 
25 // Undefined
26 typeof undefined === 'undefined';
27 typeof declaredButUndefinedVariable === 'undefined';
28 typeof undeclaredVariable === 'undefined';
29 
30 // Objects
31 typeof {a:1} === 'object';
32 
33 // 使用Array.isArray 或者 Object.prototype.toString.call
34 // 区分数组,普通对象
35 typeof [1, 2, 4] === 'object';
36 
37 typeof new Date() === 'object';

Array.isArray()判断是否为数组

 1 var ar = [];
 2 var result = Array.isArray(ar);
 3 // Output: true
 4 
 5 var ar = new Array();
 6 var result = Array.isArray(ar);
 7 // Output: true
 8 
 9 var ar = [1, 2, 3];
10 var result = Array.isArray(ar);
11 // Output: true
12 
13 var result = Array.isArray("an array");
14 document.write(result);
15 // Output: false

Object.prototype.toString.call()精准判断数据类型

1 console.log(Object.prototype.toString.call(123)) //[object Number]
2 console.log(Object.prototype.toString.call('123')) //[object String]
3 console.log(Object.prototype.toString.call(undefined)) //[object Undefined]
4 console.log(Object.prototype.toString.call(true)) //[object Boolean]
5 console.log(Object.prototype.toString.call({})) //[object Object]
6 console.log(Object.prototype.toString.call([])) //[object Array]
7 console.log(Object.prototype.toString.call(function(){})) //[object Function]

 

 
posted on 2017-08-31 17:33  xwlong  阅读(579)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3