我有使用if else语句的代码。
我想将其最小化。

var str = "";
        var isPreview=true;
        var dl = Files.findOne({_id:item._id}).link();
        var filename = item.name.split('.').pop().toLowerCase();
        if(filename == "wav" || filename == "mp3" || filename == "ogg" ) {
            str = "fa fa-file-audio-o";
            isPreview=false;
        }
        else
        if(filename == "jpg" || filename == "jpeg" || filename == "gif" || filename == "bmp" || filename == "png" )
            str = "fa fa-file-image-o";
        else
        if(filename == "flv" || filename == "wmv" || filename == "mp4" || filename == "3gp" || filename == "webm" ) {
            str = "fa fa-file-movie-o";
            isPreview=false;
        }
        else
        if(filename == "pdf" )
            str = " fa fa-file-pdf-o";
        else
        if(filename == "txt" || filename == "rtf" )
            str = " fa fa-file-text-o";
        else
        if(filename == "xls" || filename == "xlsx" ) {
            str = " fa fa-file-excel-o";
            isPreview=false;
        }
        else
        if(filename == "doc" || filename == "docx" ) {
            str = " fa fa-file-word-o";
            isPreview = false;
        }
        else
        if(filename == "ppt" || filename == "pptx" ) {
            str = " fa fa-file-powerpoint-o";
            isPreview = false;
        }
        else
        if(filename == "zip" || filename == "rar") {
            str = " fa fa-file-zip-o";
            isPreview = false;
        }
        else{
            isPreview=false;
            str = " fa fa-file";
        }
        if(Files.findOne({_id:item._id}).infected){
            isPreview=false;
            str = " fa fa-ban";
        }


执行此代码后,输出应为字符串和布尔值。
如何使用数组解决此问题?

如您所见,在每个if else语句中,它们具有不同数量的表达式。有时它只会检查1种文件类型。有时它将检查多种文件类型。

如何在此问题中使用数组或对象?

最佳答案

您可以将数据收集到数组中,并使用文件类型为哈希的对象。然后为找到的对象分配所需的值。

var fileTypes = [
        { type: ["wav", "mp3", "ogg"], preview: false, value: "fa fa-file-audio-o" },
        { type: ["jpg", "jpeg", "gif", "bmp", "png"], preview: true, value: "fa fa-file-image-o" },
        { type: ["flv", "wmv", "mp4", "3gp", "webm"], preview: false, value: "fa fa-file-movie-o" },
        { type: ["pdf"], preview: false, value: " fa fa-file-pdf-o" },
        { type: ["txt", "rtf"], preview: false, value: " fa fa-file-text-o" },
        { type: ["doc", "docx"], preview: false, value: " fa fa-file-excel-o" },
        { type: ["xls", "xlsx"], preview: false, value: " fa fa-file-word-o" },
        { type: ["ppt", "pptx"], preview: false, value: " fa fa-file-powerpoint-o" },
        { type: ["zip", "rar"], preview: false, value: " fa fa-file-zip-o" },
        { type: ["default"], preview: false, value: " fa fa-file" },
    ],
    hash = {};

fileTypes.forEach(function (a) {
    a.type.forEach(function (b) {
        hash[b] = a;
    });
});

var fileType = hash[filename] || hash.default,
    str = fileType.value,
    isPreview = fileType.preview;

10-08 17:01