zoukankan      html  css  js  c++  java
  • typeof和instanceof

    typeof一般用于检测基本类型,而对引用类型的检测一般用 instanceof

    typeof和instanceof属于运算符,和+  -  *  /是一样的。

    typeof的返回值是字符串包括:'number'、'string'、'boolean'、'undefined'、'object'、'function'。它有两种写法:typeof 1 和 typeof(1)。

    数字类型、NAN,typeof返回的值是number。比如说:typeof(1),返回值是number;

    字符串类型,typeof返回的值是string。比如typeof(“123”返回值时string);

    布尔类型,typeof返回的值是boolean。比如typeof(true)返回值时boolean;

    对象、数组、null返回的值是object。比如typeof(window),typeof(document),typeof(null)返回的值都是object;

    函数类型,返回的值是function。比如:typeof(eval),typeof(Date)返回的值都是function;

    不存在的变量、函数或者undefined,将返回undefined。比如:typeof(abc)、typeof(undefined)都返回undefined;

    typeof null  // 'object'
    typeof function() {}    // 'function'
    typeof NaN   // 'number'
    typeof ''   // 'string'

    instanceof运算符可以判断一个变量是否是某个对象(类)的实例,返回值是布尔类型

    instanceof在判断数组是,即会把数组当做Array类型,又会把数组当做Object类型,都会返回true

    object.prototype.tostring.call()

    Object.prototype.toString.call(fn);   // "[object Function]"
    Object.prototype.toString.call(date);   // "[object Date]"
    Object.prototype.toString.call(arr);   // "[object Array]"
    Object.prototype.toString.call(reg);   // "[object RegExp]"
    
    // 基本数据类型
    Object.prototype.toString.call(null);   // "[object Null]"
    Object.prototype.toString.call(undefined);   // "[object Undefined]"
    Object.prototype.toString.call(“abc”);   // "[object String]"
    Object.prototype.toString.call(123);   // "[object Number]"
    Object.prototype.toString.call(true);   // "[object Boolean]"

    判断数组

    1 用Array.isArray(arr)可以判断数组;

    2 Object.prototype.toString.call(arr);

    判断函数

    Object.prototype.toString.call(fn); 

    typeof(fn);

    判断对象

    Object.prototype.toString.call(obj);

  • 相关阅读:
    【心情】一天又一天
    【转】深度学习目标检测的整体架构描述(one-stage/two-stage/multi-stage)
    如何转载CSDN以及博客园的文章
    【转】Faster RCNN原理分析(二):Region Proposal Networks详解
    Lintcode 627
    遇黑中介打官司拿到房租的成功案例
    记录音视频不同步的问题及解决过程
    ffmpeg 使用笔记
    centos min安装后使用gclient
    剑指 Offer 26. 树的子结构
  • 原文地址:https://www.cnblogs.com/xjy20170907/p/11416806.html
Copyright © 2011-2022 走看看