What happened to this triple operator?

I have an object menuNamesthat should contain a list of menu items. If it menuNamesalready has slug, add a value, if it does not contain slug, set the value to 1. I do this to track unique names. I want to get something like:

menuNames: {
    home: 1,
    products: 10,
    contact: 1
}

this does not work (this will be contained in a loop going through each pool):

menuNames[slug] = (menuNames.hasOwnProperty(slug) ? menuNames[slug]++ : 1);
//this sets every value to 1

but this works (this will be contained in a loop going through each pool):

if(menuNames.hasOwnProperty(slug)) {
    menuNames[slug]++;
} else {
    menuNames[slug] = 1;
}
+5
source share
3 answers

menuNames[slug]++ increases the value, but also returns the original value.

You are executing menuNames[slug] =, therefore, after increasing it, the value returns to its original value.

To fix this, simply do:

menuNames[slug] = (menuNames.hasOwnProperty(slug) ? menuNames[slug]+1 : 1);

Or:

(menuNames.hasOwnProperty(slug) ? menuNames[slug]++ : menuNames[slug] = 1);
+6

, :

menuNames[slug] = (menuNames.hasOwnProperty(slug) ? ++menuNames[slug] : 1);
+3

, .

:

menuNames[slug] += (some_bool ? 1 : 0);

++ very sensitive to errors. Try recording it as an operator +=.


if it menuNames[slug]can be undefined, write it as:

menuNames[slug] = 0;
if (some_bool) {
    menuNames[slug] += 1;
}

This (in my opinion) is the clearest way to write an initialization / counter loop.

If you like single-line, you will cringe, but if you like the free code, you will be happy to see it.

+2
source

All Articles