function pyBool(v) {
let res = Boolean(v)
if (res && typeof v === "object") {
if (~[Set, Map, Array].indexOf(v.constructor)) {
if (v.length === 0 || v.size === 0) res = false
} else if (v.constructor === Object && Object.keys(v).length === 0) res = false
}
return res
}
可以实现,但没想象中那么直接。。。而且感觉依旧有疏漏之处。。。
在真正的现实中,可能就是像对待静态语言那样,预设对象具体是什么类型,然后采取相应的方法,没有 Python 那样拿来即用的爽快。
另外,判断对象无 key 时,可以这么用:
可以兼容对象为
null
和undefined
的情况。