简体   繁体   English

在函数内部更改全局变量而不调用它

[英]Changing global variable inside function without calling it

I am right now working on a messenger bot.我现在正在研究一个信使机器人。 I am still new to javascript and I been stuck with this proplem in 5 days...我还是 javascript 的新手,我在 5 天内就被这个问题困住了……

I am trying to change a value if "text" = "javascript" like this:如果 "text" = "javascript" 像这样,我正在尝试更改一个值:

  function test() {
      if (text === 'javascript') {
          githubSearch = "javascript";
      }
  };

I got a global variable named githubSearch outside the function looking like this:我在函数外有一个名为 githubSearch 的全局变量,如下所示:

var githubSearch;

Then I got a variable outside the function named githubRepo where I call githubSearch:然后我在名为 githubRepo 的函数之外得到了一个变量,我在其中调用了 githubSearch:

var githubRepo = "https://github.com/search?o=desc&q=" + githubSearch + "&s=stars&type=Repositories&utf8=%E2%9C%93";

My proplem is I need to apply the changes I make in the if statement without calling the function, how can I do this?我的问题是我需要在不调用函数的情况下应用我在 if 语句中所做的更改,我该怎么做?

When you assign a string to variable 'githubRepo', it stays as it is.当您将字符串分配给变量 'githubRepo' 时,它保持原样。 Only way to overwrite that is to reassign something to 'githubRepo'.覆盖它的唯一方法是将某些内容重新分配给“githubRepo”。

One way to do what you are trying to do is to use a function that return right URL instead of variable.做你想做的事情的一种方法是使用一个返回正确 URL 而不是变量的函数。

var searchType = 'foo';
var getRepoAddress = function(s){
   return 'https://'+s+'/index.html';
};
console.log(getRepoAddress(searchType));
searchType = 'bar';
console.log(getRepoAddress(searchType));

In this example the function takes in as an argument the searchType instead of using variable from outer function scopes.在这个例子中,函数接受searchType作为参数,而不是使用外部函数作用域中的变量。 This is considered good practice because functions can now be understood and tested as it is without needing to read lines outside the function.这被认为是一种很好的做法,因为现在可以按原样理解和测试函数,而无需读取函数外部的行。

Also, it looks like you need to split the first function to two functions so you can call just another one:此外,看起来您需要将第一个函数拆分为两个函数,以便您可以只调用另一个函数:

function getSearchType(text) {
    if (text === 'javascript') {
        return 'javascript'
    } else {
      return 'not_javascript'
    }
}

function test() {
   var gitHubSearch = getSearchType('foobar');
   // do something with gitHubSearch
}

// elsewhere, check the value again
console.log(getSearchType('javascript'));
console.log(
  getRepoAddress(getSearchType('javascript'))
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM