【问题标题】:javascript variable scope issue between two functions with callbacks带有回调的两个函数之间的javascript变量范围问题
【发布时间】:2014-10-14 17:01:16
【问题描述】:

我想连接两个数组。在下面的代码中,我只得到 txs_history 数组。

getFirstArray(function(txs) {
    getSecondArray(function(txs_history) {
        txs.concat(txs_history);
        res.send(txs_history);
    });    
});

据我所知,我可以猜测 txs var 无法在 getSecondArray 中读取,这就是它只发送 txs_history 的原因。我不知道如何解决这个范围问题。

问候,

【问题讨论】:

  • 如果txs 不在范围内,你会得到一个例外。

标签: javascript arrays concatenation scope


【解决方案1】:

txs 在作用域内,但 txs.concat() 返回一个新数组并保留原始 txs 未修改。你想要的大概是这样的:

getFirstArray(function(txs) {
    getSecondArray(function(txs_history) {
        var combined = txs.concat(txs_history);
        res.send(combined);
    });    
});

【讨论】:

    猜你喜欢
    • 2020-04-18
    • 1970-01-01
    • 2014-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多