Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/460.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在javascript中正确排序字符串数组_Javascript_Arrays_Node.js_Typescript_Sorting - Fatal编程技术网

如何在javascript中正确排序字符串数组

如何在javascript中正确排序字符串数组,javascript,arrays,node.js,typescript,sorting,Javascript,Arrays,Node.js,Typescript,Sorting,我有一个数组,如下所示 const files=['30.png','10.png','1.jpeg','2.jpeg','12.gif','4.png'] 我想按数字顺序排序,但调用sort是一个问题,因为排序时,它将如下所示: ['1.jpeg','10.png','12.gif','2.jpeg','30.png','4.png'] 如何以“正确”的方式对其进行排序,使其看起来像这样 ['1.jpeg','2.jpeg','4.png','10.png','12.gif','30.pn

我有一个数组,如下所示

const files=['30.png','10.png','1.jpeg','2.jpeg','12.gif','4.png']
我想按数字顺序排序,但调用sort是一个问题,因为排序时,它将如下所示:

['1.jpeg','10.png','12.gif','2.jpeg','30.png','4.png']
如何以“正确”的方式对其进行排序,使其看起来像这样

['1.jpeg','2.jpeg','4.png','10.png','12.gif','30.png']

我们可以使用以下代码:

const files=['30.png','10.png','1.jpeg','2.jpeg','12.gif','4.png'];
函数fileToNumber(文件){
//我们得到周期之前的所有数据,并将其转换为一个数字
返回parseInt(file.split(“.”[0],10);
}
//我们使用基于fileToNumber函数的自定义比较器进行排序
排序((a,b)=>fileToNumber(a)-fileToNumber(b));

我们可以使用以下代码:

const files=['30.png','10.png','1.jpeg','2.jpeg','12.gif','4.png'];
函数fileToNumber(文件){
//我们得到周期之前的所有数据,并将其转换为一个数字
返回parseInt(file.split(“.”[0],10);
}
//我们使用基于fileToNumber函数的自定义比较器进行排序
排序((a,b)=>fileToNumber(a)-fileToNumber(b));
函数编号部分(str){
返回parseInt(str.split('.')[0])
}
const files=['30.png','10.png','1.jpeg','2.jpeg','12.gif','4.png'];
排序((a,b)=>numberPart(a)-numberPart(b))
console.log(文件)
函数编号部分(str){
返回parseInt(str.split('.')[0])
}
const files=['30.png','10.png','1.jpeg','2.jpeg','12.gif','4.png'];
排序((a,b)=>numberPart(a)-numberPart(b))
console.log(文件)