js如何获取文件夹中的文件并随机显示
1 let requireModule = require.context( 2 "文件路径位置", 3 false, 4 /\.jpg$/ //文件后缀名 5 ); 6 let imagesNameArr = []; 7 //获取文件夹下面的所有满足需求的文件 8 for (let i = 0; i < requireModule.keys().length; i++) { 9 imagesNameArr.push(requireModule.keys()[i].substr(2, requireModule.keys()[i].length)); 10 } 11 //从上面的数组中随机筛选 12 function getRandomArrayElements(arr, count) { 13 let shuffled = arr.slice(0), i = arr.length, min = i - count, temp, index; 14 while (i-- > min) { 15 index = Math.floor((i + 1) * Math.random()); 16 temp = shuffled[index]; 17 shuffled[index] = shuffled[i]; 18 shuffled[i] = temp; 19 } 20 return shuffled.slice(min); 21 } 22 //获取到随机的文件并补全路径在页面上显示 23 let imgLinkArray = getRandomArrayElements(imagesNameArr,4) 24 for(let i=0;i<imgLinkArray.length;i++){ 25 let img = require("文件存放的路径" + imgLinkArray[i]) 26 this.phonePic.push(img) 27 }