nodejs判断对象是否包含属性,以及null, undefined

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是两个概念。

  1. 一个变量是null无法推导出变量是undefined
  2. 一个变量是undefined也无法推导出变量是null
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容