Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
188 views
in Technique[技术] by (71.8m points)

Empty set in javascript

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?

EDIT: 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");
        }
    } 
}

When running this:

showProperties(myset);

I always get only one line, regardless with which data my set has been initialized:

undefined belongs
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Best I have is

var isEmptyObject = function(v) { 
   for (x in v) {
     if (v.hasOwnProperty(x)) {
          return false;
     }
   } 
   return true;
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...