English 中文(简体)
Javascript bitwise problem
原标题:

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

最佳回答

((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) { ... }

问题回答

暂无回答




相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.

热门标签