简体   繁体   中英

Strange behaviour on checking condition in javascript

I am writing a code to draw a hexagonal mesh using svg on the screen,the reason I have use a single hexagon instead of a pattern is that I eventually want to make every single hexagon a object to reference to

I have sort of drawn the hexagons using some math and point references.

So instead of making this complicated then it really is by trying to explain my code, here is my code https://jsfiddle.net/Snedden27/9nnrt7hp/8/ ,

My problem is function drawHexAround(cent) //line 41 , the function is suppose to draw hexagon around the hexagon with centroid '@cent'

Here is the checking condition:

if (!contains(drawnCentroids,centroidNew)) {
    makeHex(centroidNew);
    drawnCentroids.push(centroidNew);
}

and here is the function

function contains(a, obj) {
    var l = a.length;

    for (var i=0;i<l;i++) {
        // console.log(a[i],obj);
        // console.log(a[i] === obj);

        if (a[i] === obj) {
            // console.log('true');
            return true;
        }
    }

    return false;
}

It draws the hexagons alright, but it draws over existing hexagons as well inspite of me checking for the condition with contains(a,obj)

I don't understand why this condition result is always true when clearly it should result in false in some cases.

You've made the mistake that checking equality of 2 objects will check the equality of every property in the object - it doesn't!

You've not specified in your question, but from the code we can see that the objects you're checking look something like:

centroidNew = {
         cx: xRight,
         cy: yMidTop
     };

And you have an array of those which you're looking for with a loop.

The test if (a[i] === obj) { will never evaluate to true unless a[0] and obj are references to the exact same object .

To fix this, you could explicitly chck the properties, as there is only 2 of them this probably works for you

if (a[i].cx === obj.cx && a[i].cy === obj.cy) {

Here is an update of your fiddle: https://jsfiddle.net/9nnrt7hp/4/ and it now sometimes logs true from that test.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM