最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【已解决】js中如何判断dict字典变量为空

JS crifan 1379浏览 0评论
js用代码:
  componentDidMount() {
    // const { dispatch, currentUser, currentUserFunctionGroupList } = this.props;
    const { dispatch, currentUser} = this.props;
    console.log("GroupOwnerScriptCount componentDidMount: currentUser=", currentUser)

    let passedOrRestoredCurrentUser = currentUser
    console.log("!passedOrRestoredCurrentUser=", !passedOrRestoredCurrentUser)

    if (!passedOrRestoredCurrentUser) {
      const restoredCurrentUserJsonStr = localStorage.getItem("currentUser")
      console.log("restoredCurrentUserJsonStr=", restoredCurrentUserJsonStr)
log是:
GroupOwnerScriptCount componentDidMount: currentUser= {}__proto__: Object
GroupOwnerScriptCount.js:34 !passedOrRestoredCurrentUser= false
GroupOwnerScriptCount.js:48 passedOrRestoredCurrentUser= {}
即:
js中空的字典{},结果竟然不为空
所以要去搞清楚
js中如何判断空的字典
js empty dict
How to match an empty dictionary in Javascript? – Stack Overflow
去扩展Object试试
结果用:
Object.prototype.isEmpty = function() {
  console.log("Object.prototype.isEmpty: this=", this)
  const objLength = Object.keys(this).length
  console.log("objLength=", objLength)
  const isLengthZero = (objLength === 0)
  console.log("isLengthZero=", isLengthZero)
  return isLengthZero
}
但是不行,this未定义
Object.prototype.isEmpty: this= undefined
那就算了,去用:
export function isEmptyObj(obj) {
  return Object.keys(obj).length === 0
}
结果:
是可以的。
if (isEmptyObj(passedOrRestoredCurrentUser)) {
的确可以判断出是空的。
【后记】
看到:
Let’s explore objects in JavaScript – freeCodeCamp
感觉是:
初始化时写成:
let realEmptyObj = 
Object.create(null)
就可以真正创建一个空的对象(字典)了。
而不是:
let actuallyNotEmptyObj = {}
后者需要用前面的:
isEmptyObj
才能判断出是空。

转载请注明:在路上 » 【已解决】js中如何判断dict字典变量为空

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
82 queries in 0.180 seconds, using 22.14MB memory