2017-06-01 2 views
0

Wie kann ich beheben: code 2 Ausgabe Passwort ist das gleiche?Looping Eindeutige Werte - nodejs

Und warum das code 2 Passwort ist das gleiche?

Code 1:

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 }] 

Code 2:

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

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

Ausgang:

[{E-Mail: '1', Rolle: ‚normal ', Passwort: 0.4311454570811686}

,

{email: '1', Rolle: 'normal', Passwort: ,4311454570811686},

{email: '1', Rolle: 'normal', Passwort: ,4311454570811686},

{ E-Mail: '1', Rolle: 'normal', Passwort: ,4311454570811686},

{email: '1', Rolle: 'normal', Passwort: ,4311454570811686},

{email: '1', Rolle: 'normal', Passwort: 0.4311454570811686}]

+0

Bitte versuchen Sie, diese Frage leserlich zu machen. Ich kann nicht sagen, was du fragst. –

+0

warten ................... – ZERO

Antwort

0

Das Problem hier ist, dass Sie das gleiche Objekt immer wieder in das Array schieben. Technisch gesehen ergibt sich also nur das eine Objekt mit mehreren Referenzen. Versuchen Sie stattdessen Folgendes:

for (let i = 0; i < 6; i++) { 
    array.push(Object.assign({}, obj, {password: Math.random()})); 
} 

Verwenden Sie Object.assign(), um das Objekt zu "klonen".

+0

danke, du hast Recht. – ZERO

+0

können Sie mir etwas URL darüber geben. – ZERO

+0

Sicher, das [MDN Dokumente] (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) ist großartig. –