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]