As I understand, javascript passes objects as reference. So if I call a function with an object as an argument, the function can modify it. I wrote this code:
var rxjs = require("rxjs")
var obj = {}
var stream = rxjs.Observable.of(obj).
do((x)=>{x.index=isNaN(x.index)?x.index=0:x.index++; return x}).
repeat(10).
subscribe(console.log);
It defines the index
property on obj
if it does not exist yet, and increases it if it already exists. Since I'm creating an observable of an object, the observable should be able to modify the obj, right? So I should expect to see the output:
{index: 0}
{index: 1}
{index: 2}
...
but what happens is that I see
{index: 0}
{index: 0}
{index: 0}
...
It's not cloned and you can modify it, should you so desire.
Your problem is that the postfix ++
operator returns the previous value, so the value assigned to x.index
will always be zero. Use the prefix ++
instead:
do(x => { x.index = isNaN(x.index) ? x.index = 0 : ++x.index; return x; })
Also, the return value from the next
function passed to do
is ignored, so the return
is redundant.
Alternatively, you could use the postfix ++
operator and just drop the assignment to x.index
:
do(x => isNaN(x.index) ? x.index = 0 : x.index++)