Reputation: 5358
Javascript Code
var a = {};
a.test += 1; //NaN
++a.test; //NaN
Instead
var a = {};
a.test = 0;
++a.test; //1
a.test += 1; //2
I wonder if there could be anyway that can make first code sample work the same as second, i.e without an explicit assignment to 0. As in assigning default value for any property of an object to 0 instead undefined
. I'm trying to do this in node.js. So, no problem of cross browser things and old ECMA Specs.
var i;
for(i = 0; i<10; i++) {
if(a.test) {
++a.test;
} else {
a.test = 0;
++a.test;
}
//a.test = a.test || 0; (1)
//++a.test;
}
If it is possible then the inner if/else or the assignment statement(1) in the above code can be eliminated.
Upvotes: 1
Views: 3935
Reputation: 339816
There's no way to do this for any arbitrary undefined property.
For a known property name, there is a way, but DO NOT USE IT !! 1
Object.prototype.test = 0;
This will give every object an implicit .test
property with that value in it, and the first time you attempt to modify it the result will be stored in your own object:
> Object.prototype.test = 0
> a = {}
> a.test++
> a.test
1
1 Adding stuff to Object.prototype
will break stuff, including for (key in obj)
Upvotes: 3
Reputation: 119847
In the first code, you can't. Any number added to a non-number or NaN value will always result in NaN
var a = {};
a.test += 1; // undefined + 1 = NaN
++a.test; // ++(undefined) = NaN
as for the inner if
for(i = 0; i<10; i++) {
a.test = a.test || 0; //use existing value, or if undefined, 0
++a.test; //increment
}
Upvotes: 0
Reputation: 91092
This is where prototypes come in useful in javascript:
function Demo() {
}
Demo.prototype.x = 0;
> a = new Demo();
> a.x += 1
> a.x
1
> b = new Demo()
> b.x
0
Upvotes: 1
Reputation: 704
Using standard JS it's not possible to do what you're asking. Unless you prototype I guess? But I'm not experienced with Prototype.And I don't think prototyping works with Node.js
The reason for this is because js is not a typed language (i.e. we only use var to declare a variable, not int a or string b), so in order to use the ++ operator, the variable needs to be given a type through assignment.
hope that helps
Upvotes: -1
Reputation: 19581
Javascript by default defines all new variables as undefined ( if not explicitly defined ) , which is different from Number object, which you are trying to define. So you should use smth like :
for (i=0; i<10; i++) {
a.test = a.test || 0;
++a.test
}
Upvotes: 4