Reputation: 18915
I love those short js oneliners. I'd like to know if there's something logical and elegant for:
Shorter than this preferrably ;)
var obj = {} ;
//some iterative called function
obj.prop = obj.prop===undefined?0:obj.prop++;
Upvotes: 30
Views: 19349
Reputation: 1379
To initialise to 1 obj.prop = -~obj.prop
To initialize to 0 ~~++obj.prop OR ++obj.prop | 0
Upvotes: 3
Reputation: 24077
This works for both plain JS and TypeScript:
obj.prop = (obj.prop ?? 0) + 1;
Upvotes: 5
Reputation: 51
It is not possible to directly pass a variable to the function inc(obj.prop), because in javascript variables are passed by value, but you can pass the object itself and the name of the variable you want to increment.
Object.prototype.inc = function(n){ this[n]? this[n]++ : this[n] = 1; }
let obj = {};
obj.inc("prop");
// obj.prop == 1
You can also add the required fields to the object before
Object.prototype.has_fields = function(obj2){
for(let p of Object.keys(obj2)){
if(obj2[p].constructor == Object){
if(!this[p]) this[p] = {};
this[p].has_fields(obj2[p]);
}else{
if(!this[p]) this[p] = obj2[p];
}
}
return this;
}
let obj = {};
obj.has_fields({a:{b:{c:{d:{prop:0}}}}});
obj.a.b.c.d.prop++;
// obj.a.b.c.d.prop == 1
obj.has_fields({a:{b:{c:{d:{prop:0}}}}});
obj.a.b.c.d.prop++;
// obj.a.b.c.d.prop == 2
Upvotes: 1
Reputation: 9139
Similar to I Hate Lazy's answer but avoids the double assignment as Bodgan points out
++obj.prop || (obj.prop=0)
in the global scope
++window.foo || (window.foo=0)
Upvotes: 2
Reputation: 5611
A cleaner way of doing this is simply
obj.prop = obj.prop + 1 || 0;
Using the increment operator is wrong or overkill. The suffixed operator, x++
, (the example in the question) should not work at all. The prefixed, ++x
, leads to assigning twice (like saying x = x = x+1
)
Upvotes: 47
Reputation: 48771
This will result in NaN
for the first increment, which will default to 0
.
obj.prop = ++obj.prop || 0;
Upvotes: 52