js根據字尾判斷檔案檔案型別的程式碼
阿新 • • 發佈:2020-05-11
核心程式碼
<script> function getFileType(fileName) { // 字尾獲取 let suffix = ''; // 獲取型別結果 let result = ''; try { const flieArr = fileName.split('.'); suffix = flieArr[flieArr.length - 1]; } catch (err) { suffix = ''; } // fileName無後綴返回 false if (!suffix) { return false; } suffix = suffix.toLocaleLowerCase(); // 圖片格式 const imglist = ['png','jpg','jpeg','bmp','gif']; // 進行圖片匹配 result = imglist.find(item => item === suffix); if (result) { return 'image'; } // 匹配txt const txtlist = ['txt']; result = txtlist.find(item => item === suffix); if (result) { return 'txt'; } // 匹配 excel const excelist = ['xls','xlsx']; result = excelist.find(item => item === suffix); if (result) { return 'excel'; } // 匹配 word const wordlist = ['doc','docx']; result = wordlist.find(item => item === suffix); if (result) { return 'word'; } // 匹配 pdf const pdflist = ['pdf']; result = pdflist.find(item => item === suffix); if (result) { return 'pdf'; } // 匹配 ppt const pptlist = ['ppt','pptx']; result = pptlist.find(item => item === suffix); if (result) { return 'ppt'; } // 匹配 視訊 const videolist = ['mp4','m2v','mkv','rmvb','wmv','avi','flv','mov','m4v']; result = videolist.find(item => item === suffix); if (result) { return 'video'; } // 匹配 音訊 const radiolist = ['mp3','wav','wmv']; result = radiolist.find(item => item === suffix); if (result) { return 'radio'; } // 其他 檔案型別 return 'other'; } console.log(getFileType("jb51.jpg")); </script>
在chrome中F12測試發現
符合我們的要求。
上面的程式碼主要用到了js(=>) 箭頭函式
ES6標準新增了一種新的函式:Arrow Function(箭頭函式)。
為什麼叫Arrow Function?因為它的定義用的就是一個箭頭:
x => x * x
上面的箭頭函式相當於:
function (x) {
return x * x;
}
箭頭函式相當於匿名函式,並且簡化了函式定義。箭頭函式有兩種格式,一種像上面的,只包含一個表示式,連{ ... }和return都省略掉了。還有一種可以包含多條語句,這時候就不能省略{ ... }和return:
=>是es6語法中的arrow function
(x) => x + 6
相當於
function(x){
return x + 6;
};
以上就是js根據字尾判斷檔案檔案型別的程式碼的詳細內容,更多關於js字尾的資料請關注我們其它相關文章!