1、问题:fs读取文件夹文件的时候,有时顺序是乱的
而实际想要的顺序是这样的
2、思路:
主要通过js的数组中的sort方法来处理
利用replace正则区分数字与非数字来遍历a跟b,并把他们加入到数组,通过while循环截取数组来比较
3、解决:
function sort(a, b) { let ax = [], bx = []; a.replace(/(\d+)|(\D+)/g, function (_, $1, $2) { ax.push([$1 || Infinity, $2 || ""]) }); b.replace(/(\d+)|(\D+)/g, function (_, $1, $2) { bx.push([$1 || Infinity, $2 || ""]) }); while (ax.length && bx.length) { let an = ax.shift(); let bn = bx.shift(); let nn = (an[0] - bn[0]) || an[1].localeCompare(bn[1]); if (nn) return nn; } return ax.length - bx.length; } let arr=["1.jpg","10.jpg","11.jpg","12.jpg","13.jpg","14.jpg","15.jpg","2.jpg","3.jpg","4.jpg","5.jpg","6.jpg","7.jpg","8.jpg","9.jpg"] let fileList=arr.sort(sort) console.log(fileList)
//['1.jpg', '2.jpg', '3.jpg', '4.jpg', '5.jpg', '6.jpg', '7.jpg', '8.jpg', '9.jpg', '10.jpg', '11.jpg', '12.jpg', '13.jpg', '14.jpg', '15.jpg']
标签:sort,顺序,jpg,length,let,ax,排序,bx From: https://www.cnblogs.com/lovewhatIlove/p/16926222.html