我会考虑查看这种数据的数据库。但是,如果您决定不这样做,我们仍然可以相当容易地做到这一点。你需要构建一个存储数据的“映射对象”,然后查看它而不是创建一个巨大的if语句系列。这是一个带有一点数据的非常简单的例子,这种方法使用数组和每个循环来查找数据。
var mapper = [ { fileName: '000001.pdf', description: 'Title Page' }, { fileName: '00001.pdf', description: 'Project Title Page' }, { fileName: '00350.pdf', description: 'Project Financial Information' } ]; function processFile(file) { var sDesc = ''; // This really is not the most efficient way, but it is the simplest // to understand. Really you probably want to use the .find function // here instead. Or any other optimisation. mapper.forEach(function(mapping) { if (file.name === mapping.fileName) { sDesc = description; } }); return sDesc; }
在这种情况下,我们将所有数据(从文件名映射到描述)存储在数组中。然后,当我们处理文件时,我们遍历该数组以找到我们想要的信息,然后可以从那里开始。然后你可以使用它 processFile 在其他方面发挥作用。例如,您可能希望处理多个文件,因此使用上述内容我们可以执行此操作。
processFile
function processAllFiles(fileCollection) { // Again here, we would probably use a map function but // for simplicity lets go with a simple to understand loop. fileCollection.forEach(function(file) { var fileDescription = processFile(file); // Do something with this fileDescription... }); }
还有很多其他方法可以做到这一点,这使得它更容易。第一个是使用数据库,您可以告诉数据库“找到我对文件名X的描述”,它会直接为您提供。如果您的数据会随着时间的推移而增长或者数据开始变大,这是理想的选择。