简体   繁体   English

为什么我的变量没有从 JS function 获得赋值?

[英]Why my variable not getting assigned value from JS function?

** Placing My actual JS snippet" I have a small JS function in one JS file as below ** 放置我的实际 JS 片段”我在一个 JS 文件中有一个小的 JS function,如下所示

   function interest(customerRef) {
   try { 
      var customerInterest = "";         
      var baseUrl="https://test/"
      var url = baseUrl+customerRef           
      var username = "username";
      var password = "password";

      var request = new XMLHttpRequest();
      request.open("GET", url);
      request.setRequestHeader("Authorization", "Basic " + btoa(username+":"+password))
      request.send()
      request.onload=()=>
      {               
           if(request.status==200)
           {                    
                var guestJson = JSON.parse(request.response);                
                var sessions = guestJson.sessions || [];               
                var interest = sessions.filter(session => session.events)
                     .flatMap(session => session.events)
                     .filter(event => event.type === "SEARCH")
                     .map(event => event.arbitraryData.interest)[0];     
                customerInterest = interest;   
                alert("---"+customerInterest);
           } 
           else
           {
                console.log(`error ${request.status} ${request.statusText}`)
           }
      }  
      alert(customerInterest);
      return customerInterest;
 }
 catch (error) {
      console.error(error);
 }     
 }

I am calling the above function in my HTML file as below我在我的 HTML 文件中调用上述 function 如下

  customerRef = "6a789727"          
  var interest1 = "";
  interest1 = interest(customerRef);
  console.log(interest1);

I am not getting any value in " console.log(interest1) " or " alert(customerInterest); " before the return.在返回之前,我在“ console.log(interest1) ”或“ alert(customerInterest); ”中没有得到任何值。 But i am getting the expected value in " alert("---"+customerInterest); "但是我在“ alert("---"+customerInterest); ”中得到了预期值

No, you'll get an error, not just undefined .不,你会得到一个错误,而不仅仅是undefined

Running跑步

var test = "";
test = test()
console.log(test)

will yield an会产生一个

Uncaught TypeError: test is not a function

at line 2, since you just defined test to be a string ( "" ) instead of a function you could call.在第 2 行,因为您刚刚将test定义为字符串 ( "" ) 而不是 function 您可以调用。

Instead, try something like:相反,请尝试以下操作:

function greet() {
 return "Hi";
}
var test = "";
test = greet();
console.log(test);

If you evaluate this in the console, this will print out如果您在控制台中对此进行评估,这将打印出来

Hi
undefined

; ; the latter undefined comes from the return value of console.log() ;后者undefined来自console.log()的返回值;

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

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