I have an object menuNames
which should maintain a list of menu items. If menuNames
already has the slug
, increment the value, if it doesnt contain the slug
, set the value equal to 1
. I'm doing this to track unique names. I want to end up with something like:
menuNames: {
home: 1,
products: 10,
contact: 1
}
this doesnt work (this would be contained in a loop going through each slug):
menuNames[slug] = (menuNames.hasOwnProperty(slug) ? menuNames[slug]++ : 1);
//this sets every value to 1
but this does work (this would be contained in a loop going through each slug):
if(menuNames.hasOwnProperty(slug)) {
menuNames[slug]++;
} else {
menuNames[slug] = 1;
}
menuNames[slug]++
increments the value, but also returns the original value.
You are doing menuNames[slug] =
, so the value is set back to the original value after being incremented.
To fix it, just simply do:
menuNames[slug] = (menuNames.hasOwnProperty(slug) ? menuNames[slug]+1 : 1);
Or:
(menuNames.hasOwnProperty(slug) ? menuNames[slug]++ : menuNames[slug] = 1);
I guess it could work like this:
menuNames[slug] = (menuNames.hasOwnProperty(slug) ? ++menuNames[slug] : 1);
As the other answers say the problem is in the post increment.
Another way to write it is:
menuNames[slug] += (some_bool ? 1 : 0);
++
is very sensitive to bugs. Try to write it as a +=
statement.
if menuNames[slug]
can be undefined, write it as:
menuNames[slug] = 0;
if (some_bool) {
menuNames[slug] += 1;
}
This is (in my opinion) the clearest way to write an initialization/counter loop.
If you like one-liners you'll cringe, but if you like bug free code you'll be happy to see this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With