前言
遇到需求,数据在页面中使用,需要先判断数据类型。
实现
使用typeof() 函数
typeof 返回的是字符串,有六种可能:number、string、boolean、object、function、undefined
具体演示代码
1、判断基本数据类型
// 判断是否为undefined类型
if (typeof(value)=="undefined") {
toast('undefined')
}
2、字符串转为布尔类型(string → boolean)
JSON.parse('true') // true
JSON.parse('false') // false
3、判断JSON字符串
checkJSON(option) {
try {
return JSON.parse(option)
} catch (e) {
return false
}
}
use(){
var obj0 = {
"name": "故宫"
}
var obj1 = "长城"
var obj2 = '{"name":"故宫"}'
console.log(this.checkJSON(JSON.stringify(obj0))); // return json对象
console.log(this.checkJSON(obj0)); // return false
console.log(this.checkJSON(JSON.stringify(obj1))); // return 字符串:长城
console.log(this.checkJSON(obj1)); // return false
console.log(this.checkJSON(JSON.stringify(obj2))); // return json字符串:{"name":"故宫"}
console.log(this.checkJSON(obj2)); // return json对象
}