【问题标题】:Node.js variable scope outside the function函数外的 Node.js 变量范围
【发布时间】:2016-03-21 12:09:25
【问题描述】:

我对我们的 node.js 的异步属性和回调的力量做了很多阅读。

但是,我不明白如果我定义一个函数并在该函数内部更改变量的值,那么为什么它在函数外部不可用。

让我通过一个示例来说明我一直在编写的代码。

var findRecords = function(db, callback) {

var cursor =db.collection('meta').find({"title":"The Incredible Hulk: Return of the Beast  [VHS]"}, {"asin":1,_id:0}).limit(1);
pass="";
cursor.each(function(err, doc) {
      assert.equal(err, null);
      if (doc != null) {
          var arr =  JSON.stringify(doc).split(':');
          key = arr[1];
          key = key.replace(/^"(.*)"}$/, '$1');
          pass =key;
          console.log(pass); //Gives correct output
      } 

   });

   console.log(pass)  //Does not give the correct output

};



MongoClient.connect(url, function(err, db) {
  assert.equal(null, err);

  findRecords(db, function() {
      db.close();
  });
}); 

在这里,当在函数内部打印 pass 的值时,它会给出分配的新值,但在函数外部第二次打印时,它不会给出新值。

如何解决这个问题。

【问题讨论】:

标签: node.js


【解决方案1】:
let pass = 'test';

[1, 2, 3].map(function(value) {
  let pass = value;
  // local scope: 1, 2, 3
  console.log(pass);
}); 

console.log(pass); // => test

// ------------------------------

let pass = 'test';

[1, 2, 3].map(function(value) {
  pass = value;
  // local scope: 1, 2, 3
  console.log(pass);
}); 

// the last value from the iteration
console.log(pass); // => 3

// ------------------------------

// we omit the initial definition

[1, 2, 3].map(function(value) {
  // note the usage of var
  var pass = value;
  // local scope: 1, 2, 3
  console.log(pass);
}); 

// the variable will exist because `var`
console.log(pass); // => 3

// ------------------------------

// we omit the initial definition

[1, 2, 3].map(function(value) {
  // note the usage of var
  let pass = value;
  // local scope: 1, 2, 3
  console.log(pass);
}); 

// the variable will not exist because using let
console.log(pass); // => undefined

【讨论】:

    【解决方案2】:

    尝试使用:

    var pass="";
    var that = this;
    cursor.forEach(function(err, doc) {
          assert.equal(err, null);
          if (doc != null) {
              var arr =  JSON.stringify(doc).split(':');
              key = arr[1];
              key = key.replace(/^"(.*)"}$/, '$1');
              pass =key;
              console.log(pass); //Gives correct output
          } 
    
       }, that);
    console.log(pass);
    

    【讨论】:

      【解决方案3】:

      而不是 pass=""
      首先声明它并尝试这个 var pass="";

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-10-06
        • 2012-06-06
        相关资源
        最近更新 更多