簡體   English   中英

變量范圍和更改節點中的全局變量

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

我在函數中有一個if-else塊。 結果取決於q的值。 如果q的值是“定義明確的查詢”(例如:localhost:1235 / docs / q?beaven),則應打印4。 q = {}(例如:localhost:1235 / docs),結果應將codemessage作為其屬性(具有各自的值)並作為JSON傳遞。

但是,這沒有發生。 我搞砸了范圍。 輸出為: ""

 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 === {})永遠不會為真,因為===測試兩者是否是完全相同的對象(如果它們具有相同的屬性,則不是),在這里永遠不會如此,因為q{}總是不同的對象。

您可能需要測試q上是否存在特定屬性。 或者您可以測試if (Object.keys(q).length === 0)來查看q是否為空對象。 但是,我認為可能最適合您的代碼的是查看您在q上尋找的特定屬性是否存在。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM