简体   繁体   English

变量范围和更改节点中的全局变量

[英]Scope of variables and changing the global variable in node

I have an if-else block in the function. 我在函数中有一个if-else块。 The result depends on the value of q. 结果取决于q的值。 If the value of q is a "well-defined query"(ex:localhost:1235/docs/q?beaven) then it should print 4. If the query is not well defined ie. 如果q的值是“定义明确的查询”(例如:localhost:1235 / docs / q?beaven),则应打印4。 q={}(ex: localhost:1235/docs), the result should have code and message as their properties(with their respective values) and passed as JSON. q = {}(例如:localhost:1235 / docs),结果应将codemessage作为其属性(具有各自的值)并作为JSON传递。

But, it is not happening. 但是,这没有发生。 I am messing up with the scope. 我搞砸了范围。 The Output is: "" 输出为: ""

 function doSearch(app){

  return errorWrap(async function(req, res) {
    const q = req.query || {};
    try {
      // let results = await app.locals.finder.find(q);
      let results = "";
      // console.log(q);
      if(q === {}){
         results = {
          code: "BAD_PARAM",
          message: "required query parameter \"q\" is missing"
         };
         res.json(results);
      // results = await app.locals.finder.find(q);
      }else{
        results == 4;
        res.json(results);
      }

    }
    catch (err) {
      const mapped = mapError(err);
      res.status(mapped.status).json(mapped);
    }
  });

}

if (q === {}) will never be true because === tests to see if the two are the exact same object (not if they have the same properties) and that will never be the case here because q and {} are always different objects. if (q === {})永远不会为真,因为===测试两者是否是完全相同的对象(如果它们具有相同的属性,则不是),在这里永远不会如此,因为q{}总是不同的对象。

You probably need to test if specific properties are present on q or not. 您可能需要测试q上是否存在特定属性。 Or you can test if (Object.keys(q).length === 0) to see if q is an empty object. 或者您可以测试if (Object.keys(q).length === 0)来查看q是否为空对象。 But, I think probably what is best for your code is to see if the specific properties you're looking for on q are present or not. 但是,我认为可能最适合您的代码的是查看您在q上寻找的特定属性是否存在。

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

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