可以javascript排序包含数字的字符串? [英] can javascript sort strings containing numbers?
问题描述
我正在制作一个小网页应用,其中我使用了AHK和javascript。
我让AHK成为.js文件的一组图像路径类似这样
I'm making a little web-app in which I used AHK and javascript. I make AHK a group of images paths to the .js file something like this
var importedFiles = [
"file:///F:/image1.jpg",
"file:///F:/image10.jpg",
"file:///F:/image11.jpg",
"file:///F:/image2.jpg",
]
并且应该在浏览器中查看这些图像,问题是这两种语言的排序方法与windows排序方式不同。
and these images should be viewed in the browser the problem is that the sorting method of the two languages is not like the windows sorting.
我想要的是javascript对变量中的文件进行排序,以便它们像在Windows中一样被查看
What I want is javascript sort the file in the variable so that they are like they are viewed in windows like this
var importedFiles = [
"file:///F:/image1.jpg",
"file:///F:/image2.jpg",
"file:///F:/image10.jpg",
"file:///F:/image11.jpg",
]
顺便说一句:我已经搜索过之前发布的功能,但它只适用于数字,包含数字的字符串就像这种情况一样
BTW : I've searched for the functions posted before but it only works with number only and strings containing number like this case
推荐答案
var importedFiles = [
"file:///F:/image1.jpg",
"file:///F:/image10.jpg",
"file:///F:/image11.jpg",
"file:///F:/image2.jpg",
]
var customSort = function (a, b) {
return (Number(a.match(/(\d+)/g)[0]) - Number((b.match(/(\d+)/g)[0])));
}
// use sort() and apply the customSort function
console.log(importedFiles.sort(customSort));
//outputs
[
"file:///F:/image1.jpg",
"file:///F:/image2.jpg",
"file:///F:/image10.jpg",
"file:///F:/image11.jpg"
]
DEMO
这篇关于可以javascript排序包含数字的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!