zoukankan      html  css  js  c++  java
  • JS中常用的方法-Json.xxx/JS的三种判断一个值的类型的办法

    JSON. parse()

    字符串转对象.

    const str = '{"name": "phoebe", "age": 20}';
    const obj = JSON.parse(str);// {name: "phoebe", age: 20}(object类型)

    JSON.stringify()

    用于把对象转化为字符串。

    typeof 123 //number
    typeof '123' //string
    typeof true // boolean
    typeof false //boolean
    typeof undefined // undefined
    typeof Math.abs // function
    typeof function () {} // function
     
    // 当遇上`null`、`Array`和通常意义上的`object`,都会返回 object
    typeof null // object
    typeof [] // object(所以判断数组时可以使用Array.isArray(arr))
    typeof {} // object
     
    // 当数据使用了new关键字和包装对象以后,数据都会变成Object类型,不加new关键字时会被当作普通的函数处理。
    typeof new Number(123); //'object'
    typeof Number(123); // 'number'
     
    typeof new Boolean(true); //'object'
    typeof Boolean(true); // 'boolean'
     
    typeof new String(123); // 'object'
    typeof String(123); // 'string'

    Object.Prototype.toString()(推荐)

    可以精准的判断对象类型。

    对于array、null、object来说,其关系错综复杂,使用 typeof都会统一返回 object 字符串,要想区别对象、数组、函数单纯使用typeof是不行的,想要准确的判断对象类型,推荐使用Object.Prototype.toString(),它可以判断某个对象值属于哪种内置类型。

    const arrs = [1,2,3];
    console.log(typeof arrs) // object
    console.log(Object.Prototype.toString.call(arrs)) // [object Array]

  • 相关阅读:
    python 文件路径拼接、判断、创建、输出
    热力图制作
    矩阵文件添加列标签
    cmd运行 ‘.py’ 文件
    hdu 2017 字符串统计
    hdu 2016 数据的交换输出
    hdu 2014 青年歌手大奖赛_评委会打分
    hdu 2013 蟠桃记
    hdu 2012 素数判定
    hdu 2011 多项式求和
  • 原文地址:https://www.cnblogs.com/maoyizhimi/p/12611609.html
Copyright © 2011-2022 走看看