开发者

javascript IF nested in a FOR loop not filtering results

I have a for loop that I am using to draw stuff from an array on to a canvas. The array holds a bunch of variables.

These variables contain qualitative values like firstName, lastName, team, etc.

I know the variables are set up correctly because my other functions using them work fine. However, I have a for loop that is suppose to be drawing circles on the canvas only if team = 'blue' .

The problem is that it is recognizing them all as being 'blue' and drawing them all, when in fact only a few are 'blue' and other are 'red', 'green', etc.

here is the code:

            ctx.fillGroups = function(g){
                for ( var i=0; i<allSeating.length; ++i ){
                    if (allSeating[i.team]=g){
                        ctx.beginPath();
                        ctx.fillPerson(allSeating[i]);
                        //alert(allSeatin开发者_StackOverflowg[i.team]);
                    }
                }
            }

With the alert() active i can see that it thinks they are all blue.

I am guessing the issue lies with the line: if (allSeating[i.team]=g) but I cant seem to get it to work. Does the check for allSeating[i.team]=g need to happen elsewhere? But then why does it think that they are all blue team anyway?

UPDATE: still not working here is a demo http://jsfiddle.net/8ryvH/1/


The issue is that = sets a variable ... use allSeating[i.team]===g

What's going on is that you are assigning g to allSeating[i.team] for every element in allSeating. The = operator does not do the same thing in JavaScript as it does in VB or SQL -- in either of those languages x = y is an equivalency test or an assignment, depending on the context. In JavaScript (and most other languages that I can think of), = is used only for assignment and == (and === in JavaScript) are used to test for equality.

== does type-casting to check equality while === does not. ("1" == 1 // true but "1" === 1 // false)


allSeating[i.team]=g is not a check: it is an assignment statement.

What about allSeating[i.team]==g instead? (Am I missing something?)

The Mozilla Developer's Network JavaScript Documentation is a great resource for this sort of thing.

Update:

As said elsewhere, there's more here than = or ===.

We noted in chat that allSeating[i].team === g is probably what you want to evaluate, but things still didn't add up.

I think the seat object is the problem, or rather the instantiation of it.

The definition has eight properties, but your instantiations have only seven.

Adding a value for the fillStyle property, as shown below, corrected the problem for me, and allSeating[i].team === g now evaluates true.

var markTwain = new Seat(758, 180, 9,fillStyle,"Mark", "Twain", 6207, "red");

Please let me know if you've got any more trouble.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜