问题描述
我已经基于通用对象类型在javascript中实现了set数据类型,如下所示:
I have implemented a set datatype in javascript based in a generic object type, like this:
function createSetFromList(list) {
var set = { };
for (var i = 0; i < list.length; i++)
set[list[i]] = true;
return set;
}
现在,我可以轻松检查给定值是否属于集合:
Now I can easily check whether a given value belongs to the set:
var users = createSetFromList(my_users);
if (user in users) allow_operation = true;
我遇到的问题是我想检查我的集合是否为空,像这样:
The problem that I have is that I would like to check if my set is empty, like this:
if ("users is empty" or user in users) allow_operation = true;
但是我不知道如何检查集合是否为空.我尝试过:
But I have no idea how to check if the set is empty. I have tried with:
if (users == { } || user in users) allow_operation = true;
但是显然逻辑表达式的第一部分从来都不是真的.
But apparently the first part of the logical expression is never true.
我想这与以下事实有关:当用户为空时,它仍然被初始化为一个对象,没有任何设置元素,并且一个对象永远不会等于另一个对象?
I guess it has to do with the fact that when users is empty, it is still initialized as an object, without any set elements, and an object is never equal to another object?
是否有任何变通办法来检查我设置的实现是否为空?
Is there any workaround to check for emptiness for my set implementation?
我已经尝试了马尔沃里奥的建议,并且发生了一些奇怪的事情.我对其进行了一些修改,以查看发生了什么:
I have tried out Malvolio's suggestion, and something strange is going on. I have modified it a bit to see what is happening:
function showProperties(v) {
for (x in v) {
if (v.hasOwnProperty(x)) {
$.log(x + " belongs");
} else {
$.log(x + " does not belong");
}
}
}
运行时:
showProperties(myset);
我总是只得到一行,而不管我的集合已初始化了哪些数据:
I always get only one line, regardless with which data my set has been initialized:
undefined belongs
推荐答案
最好的是
var isEmptyObject = function(v) {
for (x in v) {
if (v.hasOwnProperty(x)) {
return false;
}
}
return true;
};
这篇关于在javascript中设置为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!