最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Assert that an enumerable property exists on an object - Stack Overflow

programmeradmin2浏览0评论

Is it possible to use the core Node.js Assert module to check if a property exists on an object even if the property is falsy?

.html

normally we could check if an object has a property by running

var assert = require('assert');
assert(obj.prop);

but if obj.prop exists but is falsy, this won't work. I prefer using the Node.js assert module and would rather avoid other solutions, thanks.

Perhaps the best way to do this is:

    var assert = require('assert');
    assert(prop in obj);

Is it possible to use the core Node.js Assert module to check if a property exists on an object even if the property is falsy?

https://nodejs/api/assert.html

normally we could check if an object has a property by running

var assert = require('assert');
assert(obj.prop);

but if obj.prop exists but is falsy, this won't work. I prefer using the Node.js assert module and would rather avoid other solutions, thanks.

Perhaps the best way to do this is:

    var assert = require('assert');
    assert(prop in obj);
Share Improve this question edited Mar 11, 2016 at 0:12 gnerkus 12.1k7 gold badges54 silver badges74 bronze badges asked Feb 18, 2016 at 0:45 Alexander MillsAlexander Mills 101k166 gold badges537 silver badges918 bronze badges 1
  • 4 Your second snippet is best, works even if prop is set to undefined. – Jared Smith Commented Feb 18, 2016 at 0:50
Add a ment  | 

2 Answers 2

Reset to default 7

It is possible to assert that an enumerable property exists on an object. The suggested code works excellently:

var assert = require('assert');
assert(prop in obj);

If the property does not exist, an AssertionError is thrown.

When you try pare the attribute, if is undefined thrown an error, you need hasOwnProperty:

const assert = require('assert');
assert.equals(obj.hasOwnProperty('attribute'), true);
发布评论

评论列表(0)

  1. 暂无评论