nodejs判断对象是否包含属性,以及null, undefined
$ cat test.js
function printProperty(v) {
if (v.hasOwnProperty('m')) { console.log("v has property m") } else { console.log("v has no property m") }
if (v.m == null) { console.log("v.m == null") } else { console.log("v.m not== null") }
if (v.m === null) { console.log("v.m === null") } else { console.log("v.m not=== null") }
if (v.m == undefined) { console.log("v.m == undefined") } else { console.log("v.m not== undefined") }
if (v.m === undefined) { console.log("v.m === undefined") } else { console.log("v.m not=== undefined") }
}
var v = {}
if (typeof v == 'object') { console.log("v is object") } else { console.log("v is not object") }
printProperty(v)
v.m = undefined
console.log("==== v.m = undefined")
printProperty(v)
v.m = null
console.log("==== v.m = null")
printProperty(v)
v.m = false
console.log("==== v.m = false")
printProperty(v)
v.m = "X"
console.log("==== v.m = \"X\"")
printProperty(v)
运行
$ node test.js
v is object
v has no property m
v.m == null
v.m not=== null
v.m == undefined
v.m === undefined
==== v.m = undefined
v has property m
v.m == null
v.m not=== null
v.m == undefined
v.m === undefined
==== v.m = null
v has property m
v.m == null
v.m === null
v.m == undefined
v.m not=== undefined
==== v.m = false
v has property m
v.m not== null
v.m not=== null
v.m not== undefined
v.m not=== undefined
==== v.m = "X"
v has property m
v.m not== null
v.m not=== null
v.m not== undefined
v.m not=== undefined
- 判断变量是否是对象:
(typeof v == 'object') - 判断对象是否包含属性
(v.hasOwnProperty('m')) - 判断变量是否为null
(a === null) 或者 (a == null) - 判断变量是否为undefined
(a === undefined)
另外要注意的是null和undefined是两个概念。
- 一个变量是null无法推导出变量是undefined
- 一个变量是undefined也无法推导出变量是null