node.js - Why does my export stop updating when the array it references is sliced? -


i've been using node.js few years , believed understood how exports worked, edge case today has left me bit confused. code when simplified, behaved following:

a.js

var history = [] var  = 0  exports.updatehistory = function(){     history.push(i)     i++      if(history.length > 10){         history = history.slice(5)     } }  exports.history = history 

b.js

var = require('./a')  setinterval(function(){     a.updatehistory()     console.log(a.history) }, 200) 

i expected output of following:

[ 0 ] [ 0, 1 ] [ 0, 1, 2 ] [ 0, 1, 2, 3 ] [ 0, 1, 2, 3, 4 ] [ 0, 1, 2, 3, 4, 5 ] [ 0, 1, 2, 3, 4, 5, 6 ] [ 0, 1, 2, 3, 4, 5, 6, 7 ] [ 0, 1, 2, 3, 4, 5, 6, 7, 8 ] [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ] [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ] [ 5, 6, 7, 8, 9, 10 ] [ 5, 6, 7, 8, 9, 10, 11 ] [ 5, 6, 7, 8, 9, 10, 11, 12 ] [ 5, 6, 7, 8, 9, 10, 11, 12, 13 ] [ 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 ] [ 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ] [ 10, 11, 12, 13, 14, 15 ] [ 10, 11, 12, 13, 14, 15, 16 ] [ 10, 11, 12, 13, 14, 15, 16, 17 ] ... 

but instead, output:

[ 0 ] [ 0, 1 ] [ 0, 1, 2 ] [ 0, 1, 2, 3 ] [ 0, 1, 2, 3, 4 ] [ 0, 1, 2, 3, 4, 5 ] [ 0, 1, 2, 3, 4, 5, 6 ] [ 0, 1, 2, 3, 4, 5, 6, 7 ] [ 0, 1, 2, 3, 4, 5, 6, 7, 8 ] [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ] [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ] [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ] [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ] [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ] [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ] [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ] 

i able solve problem adding exports.history = history after slices each time, implying slice call somehow changing export's reference, have no idea why be. can explain behavior me?

thanks

you're updating local variable , not exported value.

change this:

exports.history = history = history.slice(5) 

the reason needed because array.slice() returns copy of portion of array , not visible outside of module (exports.history still references original array).


Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -