【问题标题】:Generate javascript object name by appending string to object通过将字符串附加到对象来生成 javascript 对象名称
【发布时间】:2015-09-10 07:57:19
【问题描述】:

我得到一个 Javascript 对象 req.files 。该对象下可以有多个文件。 req.filesobject 而不是 array

如果用户添加三个文件,对象将如下所示:

req.files.file0
req.files.file1
req.files.file2

其中file0, file1 等是另一个对象。

用户最多可以添加 15 个文件。如何检查此类对象的循环并从 req.files.fileX 读取信息?我需要支持 IE 11 和 chrome。

【问题讨论】:

  • req.files["file" + i]

标签: javascript jquery node.js


【解决方案1】:

您可以使用括号表示法通过字符串访问对象的属性。试试这个:

for (var i = 0; i < Object.keys(req.files).length; i++) {
    var file = req.files['file' + i];
    if (file) {
        // use file here...
    }
}

Example fiddle

【讨论】:

    【解决方案2】:

    所以我假设你的 req 对象看起来像这样:

    var req = {
      files: {
        file0: {},
        file1: {},
        file2: {},
        //...
        file14: {}
      }
    };
    

    如果是这样,您可以像这样引用文件:req.files['file0']

    所以你的循环可能看起来像这样:

    for (prop in req.files) {
        var file = req.files[prop];
    }
    

    但你甚至不需要使用循环:

    var getReqFile = function(x){
      return req.files['file' + x] || null;
    }
    var file = getReqFile(5);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-04
      • 1970-01-01
      • 2022-01-15
      • 2012-01-07
      • 1970-01-01
      • 2017-02-24
      • 1970-01-01
      相关资源
      最近更新 更多