【问题标题】:global variables not being found by array?数组找不到全局变量?
【发布时间】:2017-11-29 10:54:27
【问题描述】:

我以为我现在理解范围和承诺/同步性,但我很难弄清楚为什么当我在 node.js 中运行这段代码时,它会一直返回“未定义”

var playerName; 
var teamName;
var tweets = [];

function composeTweet(){

    tweets = [ playerName + ' plays basketball for the ' + teamName,
               teamName + ' want to trade for ' + playerName,
               'what if ' + playerName + ' got traded to the ' + teamName];


    function getPlayer() {
        // some code, new promise, etc ... this stuff works locally ...
        playerName = 'Tim';
    }

    function getTeam(){
        // code, promise ... works here also ...
        teamName = 'Spurs';
    }

    getPlayerName().then(function(){
        return getTeamName();
    }).then(function(){
        // sendTweet();
        console.log(tweets[1]);

    }).catch(function(fromReject) {
        console.log('error?');
    });
}

composeTweet();

这应该打印出来:

马刺想要交易蒂姆

但是我得到了:

undefined 想用 undefined 交易

在这种情况下 playerName 和 teamName 不是全局变量吗?我是否误解了如何使用承诺?如何在不使用 window.playerName 的情况下引用全局变量(我认为这在 node.js 中不起作用,对吗?)?

我大多是编程新手,如果这是重复的,我深表歉意!非常感谢!!!

【问题讨论】:

  • 代码没有真正的意义..你永远不会给playerNameteamName分配任何东西(设置它们的函数永远不会被调用),所以它们当然是未定义的。
  • tweets 中的字符串是在调用composeTweet 函数时创建的。如果您稍后更改变量值,它不会自动更新已创建的字符串。如果要获取变量的当前值,则必须使它们起作用。
  • 换句话说,如果你使用var a = "Hello"; var b = a + " World!"; a = "Goodbye Cruel";b 的值仍然是"Hello World!"——promise 与它没有任何关系。

标签: javascript node.js scope


【解决方案1】:

在您设置 tweets 变量时,playerNameteamName 值是未定义的,因为它是在您为它们分配任何值之前完成的。

您必须在playerNameteamName 获得所需值之后设置tweets 变量。

关于变量作用域和promise,代码没问题。

【讨论】:

    猜你喜欢
    • 2020-01-15
    • 1970-01-01
    • 1970-01-01
    • 2018-05-21
    • 1970-01-01
    • 2021-12-12
    • 1970-01-01
    • 2017-03-25
    • 1970-01-01
    相关资源
    最近更新 更多