node.js-在函数外使用变量

node.js-在函数外使用变量,node.js,function,variables,Node.js,Function,Variables,我是node.js的新手,我正在努力处理函数和变量 let shops = ['shop-one', 'shop-two'] function getShops(shops){ shops.forEach(element => { console.log(element) const shop = element }); } function getUrl(shop){ console.log(shop) } g

我是node.js的新手,我正在努力处理函数和变量

let shops = ['shop-one', 'shop-two']

function getShops(shops){
    shops.forEach(element => {
        console.log(element)
        const shop = element        
    });
}

function getUrl(shop){
    console.log(shop)
}

getShops(shops)

getUrl(shop) // shop is not defined
如何将一个函数中的变量用于另一个函数或函数外部以供进一步使用? 就像在我的示例中一样,我会在函数getShops中使用forEach循环中的Shopname'shop one',用于函数getUrl甚至任何函数之外


如果您能提供帮助,我将不胜感激。

您想详细说明您想要实现的要求吗?从代码来看,这有点难以猜测。我想从一个.env文件中获取商店,然后从.env(shops=shop one,shop two)中使用商店构建一个数组。在此之后,我想遍历该数组,加载该商店的特定JSON文件,并从中获取一些用于其他函数的值。有什么解释吗?url[show]=getUrl(shop)是什么;做为什么让URL={};对不起,这是一个输入错误,应该是“shop”。谢谢你的解释,但我认为这不会解决我的问题。难道没有一种方法可以在函数中声明一个可以在函数外部使用的变量,就像在python中一样吗?也许我想错了。。。但是我想使用getUrl函数从我从函数getShops获得的shop加载JSON文件。示例:通过函数getShops,我获得了商店数组和名称,然后我想加载shopname.json以在shopname.json中找到商店的url。如果我得到了url,我会使用另一个函数来传递该url,并使用该url进行进一步的操作。“难道没有一种方法可以在函数中声明一个可以在函数外部使用的变量,比如python吗?”没有。该函数是一个闭包。更多信息请参见:
let shops = ['shop-one', 'shop-two'];
// An object to store urls that will look like
// {'shop-one': 'http://aurl4shop1.com', 'shop-two': 'http://aurl4shop2.com' }
let urls = {}; 
let json = [];

function getShops(shops){
    shops.forEach(element => {
        console.log(element);
        const shop = element;
        // The following line will set a property on the url object with the value of the url.  The property name is the shop name.
        url[shop] = getUrl(shop);        
    });
}

function getUrl(shop){
    console.log(shop);
}

shops.forEach(shop => json[shop] = fetchJson(shop);

// At this point the json object should look like this:
// { 'shop-one': { /* some json */ }, 'shop-two': /* some json */ }