js用代码:
1 2 3 4 5 6 7 8 9 10 11 | 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是:
1 2 3 | GroupOwnerScriptCount componentDidMount: currentUser= {}__proto__: Object GroupOwnerScriptCount.js:34 !passedOrRestoredCurrentUser= false GroupOwnerScriptCount.js:48 passedOrRestoredCurrentUser= {} |
即:
js中空的字典{},结果竟然不为空
所以要去搞清楚
js中如何判断空的字典
js empty dict
去扩展Object试试
结果用:
1 2 3 4 5 6 7 8 | 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未定义

1 | Object.prototype.isEmpty: this= undefined |
那就算了,去用:
1 2 3 | export function isEmptyObj(obj) { return Object.keys(obj).length === 0 } |
结果:
是可以的。
1 | if (isEmptyObj(passedOrRestoredCurrentUser)) { |
的确可以判断出是空的。
【后记】
看到:
感觉是:
初始化时写成:
1 2 | let realEmptyObj = Object.create(null) |
就可以真正创建一个空的对象(字典)了。
而不是:
1 | let actuallyNotEmptyObj = {} |
后者需要用前面的:
isEmptyObj
才能判断出是空。
转载请注明:在路上 » 【已解决】js中如何判断dict字典变量为空