JavaScript数组在不想要的时候得到更新

问题描述 投票:0回答:1

我正在为小型服务器开发Discord机器人,但遇到了一个小问题。我在这里有一个模板变量:


let blankProfile = {
    ID: '',
    name: '',
    maxStrength: 10,
    currentStrength: 10,
    maxHealth: 100,
    currentHealth: 100,
    maxMana: 0,
    currentMana: 0,
    maxDefense: 0,
    currentDefense: 0,
    maxSpeed: 0,
    currentSpeed: 0,
    magic: 0,
    spells: [

    ],
    money: 0,
    position: [1,1],
    items: [

    ],
    isFighting: false,
    wins: [

    ], 
    losses: [

    ]
}

我试图更改其值。我有一个全局变量,可读取和解析JSON文档,并在此函数中添加了模板变量:

 function createFighter(userID, fighterName) {

    for(var i = 0; i < playerstats.length; i++) {
        console.log(playerstats[i].ID);
        if(playerstats[i].name == fighterName) {
            return "Please choose a different name."; //To prevent duplicates
        }
        if(playerstats[i].ID == userID) return "You already have a fighter!";
    }   
    blankProfile.name =  fighterName; //this does not "stick" outside of the function
    blankProfile.ID = userID;  //neither does this
    playerstats.push(Object.assign(blankProfile));
    fs.writeFileSync('playerstats.json', JSON.stringify(playerstats, null, 2));
    blankProfile.name = "";
    blankProfile.ID = "";
    console.log(playerstats); //returns desired output, with the correct name and ID


    return "Success!";
}

当我测试此函数时,结果证明playerstats会正确更新名称和ID,但是当我在调用该函数后尝试访问console.log(playerstats)时,它将返回名称和ID为空的数组。为什么会这样?

javascript arrays
1个回答
0
投票

问题是您正在访问和修改对象blankProfile的属性。这违反了数据不变性的原则,如果不谨慎,可能会导致代码库中的错误。我鼓励您创建一个函数(生成器,构造函数),该函数返回空概要文件(每次调用新对象时)。例如:

const getBlankProfile = () => ({
    ID: '',
    name: '',
    maxStrength: 10,
    currentStrength: 10,
    maxHealth: 100,
    currentHealth: 100,
    maxMana: 0,
    currentMana: 0,
    maxDefense: 0,
    currentDefense: 0,
    maxSpeed: 0,
    currentSpeed: 0,
    magic: 0,
    spells: [

    ],
    money: 0,
    position: [1,1],
    items: [

    ],
    isFighting: false,
    wins: [

    ], 
    losses: [

    ]
})

然后只需在要创建新对象的任何地方使用此功能。

function createFighter(userID, fighterName) {

    for(var i = 0; i < playerstats.length; i++) {
        console.log(playerstats[i].ID);
        if(playerstats[i].name == fighterName) {
            return "Please choose a different name."; //To prevent duplicates
        }
        if(playerstats[i].ID == userID) return "You already have a fighter!";
    }   
    const blankProfile = getBlankProfile();
    blankProfile.name =  fighterName; //this does not "stick" outside of the function
    blankProfile.ID = userID;  //neither does this
    playerstats.push(blankProfile);
    fs.writeFileSync('playerstats.json', JSON.stringify(playerstats, null, 2));
    console.log(playerstats); //returns desired output, with the correct name and ID


    return "Success!";
}
© www.soinside.com 2019 - 2024. All rights reserved.