javascript - About looping to create an array of objects and adding random values
为情所困
为情所困 2017-06-05 11:13:16
0
1
652

var arr = [ { email: '', role: 'normal', password: '' },
  { email: '', role: 'normal', password: '' },
  { email: '', role: 'normal', password: '' },
  { email: '', role: 'normal', password: '' },
  { email: '', role: 'normal', password: '' },
  { email: '', role: 'normal', password: '' } ]

arr.forEach(o => { o.password =Math.random() })

output :[ { email: '', role: 'normal', password: 0.16326031488429638 },
  { email: '', role: 'normal', password: 0.4941354999549721 },
  { email: '', role: 'normal', password: 0.6802056630925 },
  { email: '', role: 'normal', password: 0.5038916232454755 },
  { email: '', role: 'normal', password: 0.5232000715886489 },
  { email: '', role: 'normal', password: 0.1599782533612224 } ]

当使用 for 创建一个 对象数组

 var obj  = {
    email: '1',
    role: 'normal',
    password: ''
},array=[]

for(let i =0;i<6;i++){
     array.push(function(){
         obj.password = Math.random()
         return obj
     })   
}

output: [ { email: '1', role: 'normal', password: 0.4311454570811686 },
  { email: '1', role: 'normal', password: 0.4311454570811686 },
  { email: '1', role: 'normal', password: 0.4311454570811686 },
  { email: '1', role: 'normal', password: 0.4311454570811686 },
  { email: '1', role: 'normal', password: 0.4311454570811686 },
  { email: '1', role: 'normal', password: 0.4311454570811686 } ]

My problem is that in the second object array generated by for, the value of obj.password is not repeated

.............

为情所困
为情所困

reply all(1)
小葫芦

Reason

This question is very hidden.

obj is a quote. It means that every time you push it’s the same obj

As for why the value is always the same, it’s because what you modify is the same obj, so the value is based on the last random number.


How to modify

var arr = [ { email: '', role: 'normal', password: '' },
  { email: '', role: 'normal', password: '' },
  { email: '', role: 'normal', password: '' },
  { email: '', role: 'normal', password: '' },
  { email: '', role: 'normal', password: '' },
  { email: '', role: 'normal', password: '' } ]

arr.forEach(e => e.password = Math.random()); 

arr.forEach(console.log);

ScreenShot

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template