Vera
Vera

Reputation: 293

updating variable given a condition

Could someone please explain to me why the value of my sum2 variable is 0? I was expecting it to be 1.

var colors = [1,2,3,4,5];
var DEFINITIONS = [[1],[2],[3]];

function getAttributes(colors){
    var sumSaturated = 0;
    var sum2 = 0;

    colors.forEach(function(hsl) {
        if(hsl>2){
            sumSaturated ++;
            for(var x = 0; x<DEFINITIONS.length; x++){
                if(DEFINITIONS[x]===hsl){
                    sum2++;
                }
            }
        }
    });
    console.log(sum2, sumSaturated);
}

getAttributes(colors);

Thanks!

Upvotes: 0

Views: 41

Answers (2)

Mike Cluck
Mike Cluck

Reputation: 32511

It's because you're comparing hsl, which appears to be a number, to an array. You're effectively doing this:

hsl === [1]
hsl === [2]
hsl === [3]

If you want to compare against the individual numbers, either redefine DEFINITIONS

var DEFINITIONS = [1, 2, 3];

Or compare against the first element in it

DEFINITIONS[x][0] === hsl

Upvotes: 2

BenG
BenG

Reputation: 15154

DEFINITIONS is an array of arrays. you need if(DEFINITIONS[x][0]===hsl){

var colors = [1,2,3,4,5];
var DEFINITIONS = [[1],[2],[3]];

function getAttributes(colors){
    var sumSaturated = 0;
    var sum2 = 0;

    colors.forEach(function(hsl) {
        if(hsl>2){
            sumSaturated ++;
            for(var x = 0; x<DEFINITIONS.length; x++){
                if(DEFINITIONS[x][0]===hsl){
                    sum2++;
                }
            }
        }
    });
    console.log(sum2, sumSaturated);
}

getAttributes(colors);

Upvotes: 1

Related Questions