访问循环外部循环内的所有变量

时间:2017-07-12 18:29:30

标签: javascript node.js loops variables for-loop

所以我尝试迭代req.files这是req.files看起来像我什么时候   conosle.log(req.files)



{ logo:
   File {
     domain:
      Domain {
        domain: null,
        _events: [Object],
        members: [Object] },
     path: '/var/folders/v7/qqwh5nds511b28p8r4006pq40000gn/T/upload_3e7a4c1ee6461ad12c70140857d925cc',
     name: 'logo.png',
        },
  homeSliderImage:
   File {
     domain:
      Domain {
        domain: null,
        _events: [Object],
        members: [Object] },
     path: '/var/folders/v7/qqwh5nds511b28p8r4006pq40000gn/T/upload_424f4be7ef9a8cc1331da4ca126cd806',
     name: 'apple.png',
        }
}




这里我有我的循环,我循环通过req.files,我得到了对象的键(logo和homeSliderImage),我得到了键,我希望能够获得路径每个人。我做了但我希望能够访问此循环之外的这两个路径。如果我在循环外console.log(newPath)它只记录最后一个key.path,我想要所有这些。



    var file = req.files

        for (var key in file) {
          if (file.hasOwnProperty(key)) {
            var newPath = req.files[key].path
      
          }
        }




1 个答案:

答案 0 :(得分:2)

你需要一个像数组这样的集合,这应该在循环之外进行初始化,这样每次都不会重置该值,例如:

var paths = []; // array to hold all the paths

var file = req.files    

for (var key in file) {
  if (file.hasOwnProperty(key)) {
    paths.push(req.files[key].path); // add the value to the paths array
  }
}