简体   繁体   中英

array.push() does not what I intend to do

I am stuck with a real stupid problem. I trying to use D3.js to plot data(some scores of people) dynamically.

  1. I get the record data from a firebase database whenever a change is happening. Here I mimic this with a object with some static score data in it
  2. I add a time key/value pair in the record
  3. then I want to prepare the data for D3 by creating an array called data on which I add the record every second. I use the array push method and pass in the record with data.push(record)
  4. I put the record object onto the console which is nicely doing what intended. 5.tit but the value of time console.logged with the for loop is showing for all elements, also the past ones, the current time value (tahre than 0, 1, 2, 3, 4,.....)

I am stuck since 3 hours, believe or not.

If somebody can help me. Thanks

 var data = [];
  record = {Fanny : 40, Joe : 20};
  var time = 0;

  record["time"] = time;

  console.log(record);


  myTimer = setInterval(function () {


    time = time + 1;

    record.time = time; 

    console.log(record);

    data.push(record);


    for (i = 0; i < data.length; i++) { 
          console.log(data[i].time)

    }
  },1000);

You need to make a new record for every iteration.

Right now, you have just the same single (but repeated many times in the array) record and keep updating it.

data.push({ Fanny: 40, Joe: 20, time: time });

You may be dealing with a referencing issue, meaning that say

a is an object

a.name = 'toto';
var b = a;
b.name = 'titi';

console.log(a.name) // will output 'titi'

One way to work around that is to do the not so pretty

var b = JSON.parse(JSON.stringify(a));

to break the referencing

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM