gpt4 book ai didi

javascript - 在javascript中用数字和特殊字符对字符串进行排序

转载 作者:行者123 更新时间:2023-12-04 10:48:33 26 4
gpt4 key购买 nike

我正在尝试使用数字和特殊字符组合对字符串进行排序。

但它给出了错误的命令。

<!DOCTYPE html>
<html>
<body>

<p>Click the button to sort the array.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function MySort(alphabet)
{
return function(a, b) {
var index_a = alphabet.indexOf(a[0]),
index_b = alphabet.indexOf(b[0]);

if (index_a === index_b) {
// same first character, sort regular
if (a < b) {
return -1;
} else if (a > b) {
return 1;
}
return 0;
} else {
return index_a - index_b;
}
}
}

function myFunction() {
var items = ["AB_UI08","AB_UI03","AB_UI07","AB_UI04","AB_UI05","AB_UI014","AB_UI01","AB_UI09","AB_UI010","AB_UI011","AB_UI012","AB_UI013","AB_UI06","AB_UI016","AB_UI07","AB_UI018","AB_UI019","AB_UI015","AB_UI020","AB_UI02"

],
sorter = MySort('*!@_.()#^&%-=+01234567989abcdefghijklmnopqrstuvwxyz');

console.log(items.sort(sorter));
}
</script>

</body>
</html>

它给出了以下回应。
[“AB_UI01”、“AB_UI010”、“AB_UI011”、“AB_UI012”、“AB_UI013”、“AB_UI014”、“AB_UI015”、“AB_UI016”、“AB_UI017”、“AB_UI018”、“AB_UI010” AB_UI020”、“AB_UI03”、“AB_UI04”、“AB_UI05”、“AB_UI06”、“AB_UI07”、“AB_UI08”、“AB_UI09”]

未排序数组:
[“AB_UI08”、“AB_UI03”、“AB_UI07”、“AB_UI04”、“AB_UI05”、“AB_UI014”、“AB_UI01”、“AB_UI09”、“AB_UI010”、“AB_UI011”、“AB_UI012”、“AB_UI” AB_UI06","AB_UI016","AB_UI017","AB_UI018","AB_UI019","AB_UI015","AB_UI020","AB_UI02"]

预期输出:
[“AB_UI01”、“AB_UI02”、“AB_UI03”、“AB_UI04”、“AB_UI05”、“AB_UI06”、“AB_UI07”、“AB_UI08”、“AB_UI09”、“AB_UI010”、“AB_UI011”、“AB_UI012” AB_UI013"、"AB_UI014"、"AB_UI015"、"AB_UI016"、"AB_UI17"、"AB_UI018"、"AB_UI019"、"AB_UI020"]

感谢您的建议。

最佳答案

如果您喜欢按组排序,例如字母和/或数字,您可以使用 String#localeCompare 选项进行排序。 .

var array = ["AB_UI08","AB_UI03","AB_UI07","AB_UI04","AB_UI05","AB_UI014","AB_UI01","AB_UI09","AB_UI010","AB_UI011","AB_UI012","AB_UI013","AB_UI06","AB_UI016","AB_UI07","AB_UI018","AB_UI019","AB_UI015","AB_UI020","AB_UI02"];

console.log(array.sort((a, b) => a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' })));
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 在javascript中用数字和特殊字符对字符串进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59589337/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com