admin管理员组文章数量:1419186
I'm using Appcelerator and I want to know if my dictionary in JS is empty.
I've tried this:
var options = {};
// Option 1
Object.keys(options).length
1
//Option 2
isEmpty(options)
false
function isEmpty(ob){
for(var i in ob){ if(ob.hasOwnProperty(i)){return false;}}
return true;
}
//Option 3
JSON.stringify(options) === '{}'
false
I'm using Appcelerator and I want to know if my dictionary in JS is empty.
I've tried this:
var options = {};
// Option 1
Object.keys(options).length
1
//Option 2
isEmpty(options)
false
function isEmpty(ob){
for(var i in ob){ if(ob.hasOwnProperty(i)){return false;}}
return true;
}
//Option 3
JSON.stringify(options) === '{}'
false
Share
Improve this question
edited Feb 10, 2016 at 13:20
Fokke Zandbergen
3,8661 gold badge13 silver badges28 bronze badges
asked Feb 8, 2016 at 13:00
amurciaamurcia
79110 silver badges27 bronze badges
9
-
What does
console.log.log(options)
show you? The first option is telling you there is one property, so what is it? Log it and see. – nnnnnn Commented Feb 8, 2016 at 13:03 - I don't know why shows one property. The console shows: options = {} – amurcia Commented Feb 8, 2016 at 13:06
-
1
But what is the key? Log
Object.keys(options)
, not the .length, so we can see what the first key is. Could that property (whatever it is) have a value that was set to undefined, or to a function? Either would be ignored by JSON. stringify. – nnnnnn Commented Feb 8, 2016 at 13:23 - 1 Thank you, you're right. I had a key with undefined value. – amurcia Commented Feb 8, 2016 at 14:44
- 1 @FokkeZandbergen done! – amurcia Commented Feb 10, 2016 at 13:28
1 Answer
Reset to default 3Finally I found the problem: I added one key with value 'undefined' and the JSON.stringify()
function didn't show me that key.
So, this function Object.keys(options).length
works perfectly.
Caution with keys with value 'undefined', check this with this function Object.keys(options)
because JSON.stringify
return an empty dictionary {}
var dict = {
cat: undefined
}
Ti.API.debug("Dict: " + JSON.stringify(dict)) > Dict: {}
Ti.API.debug("Keys: " + Object.keys(options).length) > Keys: 1
Ti.API.debug("Keys str: " + Object.keys(options)) > Keys: cat
var dict = {}
Ti.API.debug("Dict: " + JSON.stringify(dict)) > Dict: {}
Ti.API.debug("Keys: " + Object.keys(options).length) > Keys: 0
Ti.API.debug("Keys str: " + Object.keys(options)) > Keys:
本文标签: JavaScriptDictionary is emptyStack Overflow
版权声明:本文标题:JavaScript - Dictionary is empty - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745290708a2651775.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论