1

I have a problem while using bitwise in javascript. I don't know if I'm going about this the wrong way. But here goes.

I have 4 main categories. With id 1,2,4,8.

A item in my object has a property with the total of the categories it's a member of. ie.

{ item: { name: 'lorem', c: 7 }} //member of category 1,2,4

I have variable (n) that holds then combined number of active categories. In this case if all categories as active the number is 15.

Now if I change n to 11 (category 1,2,8 is active) I'm trying to determine what items are active. Like this

for (x in items) {
            item = items[x];
            if ((n & item.c) == item.c) {
                //active
            } else {
                //inactive
            }
        }

This doesn't work properly. For example if item.c is 9 (Member of 1,8) the if statement will return true. As it should. But if item.c is 7 (Member of 1,2,4) the if statement returns false. This is my problem. 7 should return true since category 1 and 2 is still active.

Or is this the wrong approach ?

..fredrik

2
  • aside: avoid for...in for iterating Arrays, it doesn't do what you'd expect. It may work here if you don't care about what order you get the items in, but it'll also blow up if anyone fiddles with the Object prototype. Stick with the old-school C for(var i= 0; i<items.length; i++) loop. Commented Nov 28, 2009 at 12:23
  • thanks. But this is an JSON object loaded from server side. And about the old-school for loop. You should set length as an var. Since for each loop it performs i looks at the array and then the length. This is especially if you have have to calculate the length. var i, l = items.length; for(i = 0; i < l; i++) {} And according to JSLint you should also use i += 1 instead of i++ Commented Nov 28, 2009 at 14:03

1 Answer 1

3

((n & item.c) == item.c) means "true if all the bits set in item.c are also set in n". If item.c is 7 and n is 11, bit 4 is set in item.c but not in n so the result is false.

It sounds like you want if (n & item.c) { ... }

Sign up to request clarification or add additional context in comments.

1 Comment

But given that item.c will take only 1,2,4 or 8 as its value, isn't if((n & item.c) == item.c) equivalent to if(n & item.c)?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.