I'm passing a string which looks something like: "John.Doe.100.Newbie-David.Miller.250.Veteran-" to the SplitDatabase function which splits the string appropriately and assigns the values to the UserDataEntry object. The UserDataEntry object is then pushed in to the global UserData array which is supposed to store all the user data.
For some reason though, the UserData.push(UserDataEntry) part seems to be overwriting previous data in the UserData array. The alert in the 1st loop shows the correct data as it loops, but alert in the second loop at the bottom just shows the last record over and over again.
I'm not sure why this is?
var UserData = []; function SplitDatabase(result) { var RawUsers = result.split('-'); var UserDataEntry = {}; for (var i = 0; i < (RawUsers.length - 1); i++) { var tempUserData = RawUsers[i].split('.'); for (var x = 0; x < (tempUserData.length); x++) { switch (x) { case 0: UserDataEntry.firstname = tempUserData[x]; break; case 1: UserDataEntry.lastname = tempUserData[x]; break; case 2: UserDataEntry.points = tempUserData[x]; break; case 3: UserDataEntry.rank = tempUserData[x]; UserData.push(UserDataEntry); alert(UserData[i].firstname); break; } } } for (var i = 0; i < (UserData.length); i++) { alert(UserData[i].firstname); } }
The Array. push() method has to be passed a String value, else it will override all values in the array to the last value pushed.
push() The push() method adds one or more elements to the end of an array and returns the new length of the array.
push() adds item(s) to the end of an array and changes the original array. unshift() adds an item(s) to the beginning of an array and changes the original array. splice() changes an array, by adding, removing and inserting elements.
To push an object into an array, call the push() method, passing it the object as a parameter. For example, arr. push({name: 'Tom'}) pushes the object into the array. The push method adds one or more elements to the end of the array.
Calling push
will not copy your object, because JavaScript Object
s are passed by reference: you're pushing the same Object
as every array entry.
You can fix this easily by moving the var UserDataEntry = {};
inside the loop body, so that a new object is created each loop iteration:
for (var x = 0; x < (tempUserData.length); x++) { var UserDataEntry = {};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With