zoukankan      html  css  js  c++  java
  • 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]
     
  • 相关阅读:
    Axure chrome 安装及已损坏的解决方法
    Ubuntu16.04上使用git
    ubuntu初探
    nginx入门笔记
    更改element-UI按钮默认样式
    js深拷贝与浅拷贝的区别及实现
    安装mysql-python的遇到的问题
    facebook atc弱网环境搭建和踩坑总结
    验证码识别 Tesseract的简单使用和总结
    selenium 基础(一)
  • 原文地址:https://www.cnblogs.com/xwlong/p/7459458.html
Copyright © 2011-2022 走看看