• 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);

  • 相关阅读:
    实现第三方系统单点登录
    python爬虫
    webot设备motor的api
    webots学习
    python学习算术运算
    python快捷键与命令函数
    python学习构造和析构
    python学习对象相关的bif
    python学习对象:拾遗
    matlab基础知识
  • 原文地址:https://www.cnblogs.com/xjy20170907/p/11416806.html
Copyright © 2020-2023  润新知