Copyright © https://mongoose-os.com

Mongoose OS Forum

frame
ATTENTION! This forum has moved to:

https://community.mongoose-os.com

Do not post any new messages.

Array of objects in javascript

jstevewoodjstevewood California
edited May 2018 in Mongoose OS

Hi All,

This may be just a javascript question, but any help that can be provided would be greatly appreciated. I am trying to create an array of objects in javascript. The simplest reduction looks like this:

let i=0;
let zs ={first:0, second:0, third:0};
let sk=[];
for (i=0;i<4;i++){
  sk[i]=Object.create(zs);
}
for (i=0;i<4;i++){
  zs.first=i*1;
  zs.second=i*2;
  zs.third=i*3;
  print("zs", i, zs.first,zs.second,zs.third);
  sk[i]=zs;
  print ("sk", i, sk[i].first,sk[i].second,sk[i].third);
  }
print("");  
for (i=0;i<4;i++){
  print ("sk", i, sk[i].first,sk[i].second,sk[i].third);
}

The results I get look like this:

[May 25 21:32:53.387] zs 0 0 0 0
[May 25 21:32:53.390] sk 0 0 0 0
[May 25 21:32:53.394] zs 1 1 2 3
[May 25 21:32:53.397] sk 1 1 2 3
[May 25 21:32:53.401] zs 2 2 4 6
[May 25 21:32:53.406] sk 2 2 4 6
[May 25 21:32:53.409] zs 3 3 6 9
[May 25 21:32:53.413] sk 3 3 6 9
[May 25 21:32:53.415]
[May 25 21:32:53.417] sk 0 3 6 9
[May 25 21:32:53.420] sk 1 3 6 9
[May 25 21:32:53.424] sk 2 3 6 9
[May 25 21:32:53.427] sk 3 3 6 9

It seems like the last object assignment fills the whole array. I am trying to get an array of individual object assignments as demonstrated with the first eight lines of results. Any ideas on how to achieve the objective?

Thanks,

JSW

Comments

  • nliviunliviu Romania

    The assignment operation of objects sk[i]=zs; passes a reference to sk[i], not a value. Hence, if you assign zs to sk[0] and modify zs afterwards, sk[0] will show the newest value of zs.
    The right way will be

            sk[i].first = i * 1;
            sk[i].second = i * 2;
            sk[i].third = i * 3;
    
    Thanked by 2pwiner jstevewood
  • jstevewoodjstevewood California

    Thank you nliviu. Unless you know what to what look for, it's hard to get a good description of this.

    JSW

Sign In or Register to comment.