-1

what's the difference between the following two sections of code?

one.

        var arr = [70,80,150,310,260,100,78];
        var pointArr=[];
        var point={};

        for (var i = 0; i < arr.length; i++) {
          point.x=i*80;
          point.y=(arr[i]/600)*240;
          pointArr.push(point);
           console.log(point);
         console.log(pointArr);

        }

two

        var arr = [70,80,150,310,260,100,78];
        var pointArr=[];


        for (var i = 0; i < arr.length; i++) {
        //diff
            var point={};
          point.x=i*80;
          point.y=(arr[i]/600)*240;
          pointArr.push(point);
           console.log(point);
         console.log(pointArr);

        }

results: one enter image description here

two enter image description here

Paul Dixon
  • 295,876
  • 54
  • 310
  • 348
黄养滕
  • 1
  • 1
  • In your first example it's only using the last value (78) and index (6) of the array. Probably using values of earlier experimenting? If you can reproduce that with a [fiddle](http://jsfiddle.net) then please add that to your question. – yezzz May 05 '17 at 10:58

3 Answers3

0

For code one, point is initialised once. Whereas for code two, it is initialised for every loop.

rishipuri
  • 1,498
  • 11
  • 18
0

when you initialize the variable inside the loop, it will initialize (reset) with each iteration. This means that you will push data to an empty object and log that object every time the for loop runs, instead of continuously pushing to the object that was created outside the loop in your first example. Does that make sense?

MikkelTN
  • 26
  • 3
0

In JavaScript Objects are passed by reference. Whereas primitive types are passed by value and are immutable.

So in your first code example the variable point will be stored in memory as a reference in form of a pointer. Inside the loop you keep pushing the same reference to pointArr. Changing the x and y property of point will just change the referenced value. This has nothing to do with the loop itself.

Just change your first example to the following:

var arr = [70,80,150,310,260,100,78];
var pointArr=[];
var point={};

for (var i = 0; i < arr.length; i++) {
  point.x=i*80;
  point.y=(arr[i]/600)*240;
  pointArr.push(point);
}

window.setTimeout(function() {
  point.x = 'foo';
  point.y = 'bar';
  console.log(pointArr);
}, 2000)

By looking at the console output you can tell that you have several occurrences of the same reference inside pointArr.

By re-declaring point inside your loop, like you did in the second example, you simply created a new reference for each point. You may want to take a look at the following link which explains this in more detail.

Primitive Types and Reference Types

Hope that helps.

DavidDomain
  • 14,976
  • 4
  • 42
  • 50