0

I have function something below,

function test(){
    const obj = {}
    const arr = []

    for(let i = 0; i < 100; i++) {
        obj.i = i
        arr.push(obj)
    }

    return arr
} 

const res = test();
console.log(res);

which returns

[{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99}]

but why it not return

[{"i":0},{"i":1},...,{"i":99}]

any reason.

0stone0
  • 34,288
  • 4
  • 39
  • 64
KARTHIKEYAN.A
  • 18,210
  • 6
  • 124
  • 133

1 Answers1

2

You are replacing the value each time it is looping.Do like this

function test(){
     const arr = []
     for(let i = 0; i < 100; i++) {
         const obj = {}
        obj.i = i
        arr.push(obj)
     }

    return arr
} 

const res = test();
console.log(res);

MenTalist
  • 84
  • 8