【问题标题】:give value to variable inside a function and access outside of it给函数内部的变量赋值并在函数外部访问
【发布时间】:2019-05-18 14:21:38
【问题描述】:

我有简单的表单验证,我正在做的是:读取 json 文件,从中获取属性(数组)然后检查它是否包含用户生成数组的每个元素,仅此而已,例如:

[1,2,3,4,5] (json file array)
[1,2,3,4,5,6] (U.G array) //it must return false

所以我使用这个代码来实现这个:

 const contains = (arr1, arr2) => {
  arr2.every(v => arr1.indexOf(v) !== -1)
 }
   var match;
   fs.readFile('../tags.json', 'utf8', (err, data)=>{

     var JsonData = JSON.parse(data);
     var tagsArray = JsonData.tags;
     console.log(tagsArray)
     console.log(tags)
     if(tagsArray instanceof Array){
       console.log('tagsArray is array')
     }
      if(!contains(tagsArray, tags)){
        match = false
      }   
      else{
        match = true
      }
     console.log(match + ' blah1')

   });

   console.log(match + ' blah2')
 if(match == false){
    return res.status(409).send({
      message: 'Do not provide your own tags'
    });
  }

但它每次都返回 false,因为 contains(tagsArray, tags) 每次都未定义。那么这有什么线索呢?

【问题讨论】:

  • 先尝试使用console.log(data)进行调试。这可能是你的第一个问题,没有得到正确的数据。
  • 这是因为当我记录 tagsArray 时,它给了我预期的结果
  • 您不恰当地使用了contains。您应该改用数组方法。
  • 我相信包含检查项目是否是数组的元素。您将需要遍历您的数组。
  • 天哪,包含不是方法,而是我创建的函数

标签: javascript arrays node.js json express


【解决方案1】:

fs.readFile 回调中的 match 变量与在外部范围中声明的变量 match 相同,这要归功于闭包。 所以,问题出在内在逻辑上。

【讨论】:

    【解决方案2】:

    参见fs.readFile document:异步读取文件的全部内容。

    所以执行顺序是:

    或者你可以使用fs.readFileSync()

    【讨论】:

    • 将第二步移到块中会导致错误
    猜你喜欢
    • 2017-06-01
    • 2017-03-08
    • 1970-01-01
    • 1970-01-01
    • 2017-02-02
    • 1970-01-01
    • 2013-08-16
    • 2020-03-03
    • 2015-04-29
    相关资源
    最近更新 更多