zoukankan      html  css  js  c++  java
  • typeof 都有哪些返回值?

    MDN介绍

    typeof操作符返回一个字符串,指示未经计算的操作数的类型。

    语法

    typeof operand

    operand 是一个表达式,表示对象或原始值,其类型将被返回。

    再来看一下有哪些原始值.

    原始值: null,undefined,boolean,number,string,symbol (ECMAScript 6 新定义)

    typeof 的所有返回值除了原始值还有Object,function,Implementation-dependent

      Object很好了解,除了直接量,都是对象,甚至在浏览器端的 null,也是源自 window.null 也是个对象.

      function 是 ECMA-262条款中实现的

      Implementation-dependent 表示该对象时由js环境提供的宿主对象

    优点:

      可以有效区分 undefined , function , symbol 和 object 

    缺点:

      由于 1 和 new Number(1) 的存在,typeof无法准确判断对象的类型

      typeof  正则表达式 === 'function' 

    例子:

    // Numbers
    typeof 37 === 'number';
    typeof 3.14 === 'number';
    typeof Math.LN2 === 'number';
    typeof Infinity === 'number';
    typeof NaN === 'number'; // 尽管NaN是"Not-A-Number"的缩写
    typeof Number(1) === 'number'; // 但不要使用这种形式!
    
    // Strings
    typeof "" === 'string';
    typeof "bla" === 'string';
    typeof (typeof 1) === 'string'; // typeof总是返回一个字符串
    typeof String("abc") === 'string'; // 但不要使用这种形式!
    
    // Booleans
    typeof true === 'boolean';
    typeof false === 'boolean';
    typeof Boolean(true) === 'boolean'; // 但不要使用这种形式!
    
    // Symbols
    typeof Symbol() === 'symbol';
    typeof Symbol('foo') === 'symbol';
    typeof Symbol.iterator === 'symbol';
    
    // Undefined
    typeof undefined === 'undefined';
    typeof declaredButUndefinedVariable === 'undefined';
    typeof undeclaredVariable === 'undefined'; 
    
    // Objects
    typeof {a:1} === 'object';
    
    // 使用Array.isArray 或者 Object.prototype.toString.call
    // 区分数组,普通对象
    typeof [1, 2, 4] === 'object';
    
    typeof new Date() === 'object';
    
    // 下面的容易令人迷惑,不要使用!
    typeof new Boolean(true) === 'object';
    typeof new Number(1) === 'object';
    typeof new String("abc") === 'object';
    
    // 函数
    typeof function(){} === 'function';
    typeof class C{} === 'function'
    typeof Math.sin === 'function';
    typeof new Function() === 'function';
    

      

  • 相关阅读:
    docker search 报错
    mgo连接池
    饿了么这样跳过Redis Cluster遇到的“坑”
    Linux Swap的那些事
    epoll使用详解(精髓)(转)
    select、poll、epoll之间的区别总结[整理](转)
    git merge 和 git rebase 小结(转)
    linux查看端口占用情况
    [LeetCode] Combinations——递归
    C++中的static关键字的总结(转)
  • 原文地址:https://www.cnblogs.com/xiaxiaodong/p/8276128.html
Copyright © 2011-2022 走看看