变量的值不会改变

时间:2015-12-05 11:40:59

标签: javascript

我有这段代码:

function loadCharacter(characterName) {
    var characterObject = {"Tri":"t"};

    socket.emit("loadCharacter", { "name" : characterName },function(dataFromServer) {
        console.log(dataFromServer);
        characterObject = dataFromServer;
    });

    return characterObject;
};

var localCharacter = loadCharacter("Gabriella");
console.log(localCharacter);

console.log(dataFromServer)显示来自服务器的数据,但console.log(localCharacter)显示原始值{"Tri":"t"},而不是dataFromServer的值。< / p>

如何更改characterObject的值并将其返回?

1 个答案:

答案 0 :(得分:0)

这是因为

characterObject = dataFromServer;

...在

之后运行
return characterObject;