Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
739 views
in Technique[技术] by (71.8m points)

javascript - Push is overwriting previous data in array

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);
    }

}
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Calling push will not copy your object, because JavaScript Objects 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 = {};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...