gpt4 book ai didi

javascript 排序不能正确处理字符串

转载 作者:行者123 更新时间:2023-12-02 14:12:13 25 4
gpt4 key购买 nike

我使用 JavaScript 代码对页面元素输入中的字符串进行排序,如下所示:

a=document.getElementsByTagName("textarea");
input=a[0].innerHTML;
input=input.split(',');
input=input.sort();
alert(input);
var str=input.join();
str=str.replace(" ","");

输入字符串包含逗号和空格,因此如果输入如下:

yet, must, has, wants, would, some, are, let, own, can, could, which, his, had, got, our, only, also, every, after, other, may, you, them, while, ever, what, get, its, why, their, her, him, just, say, this, than, have, able, least, like, whom, nor, cannot, into, among

输出是:

able, after, also, among, are, can, cannot, could, ever, every, get, got, had, has, have, her, him, his, into, its, just, least, let, like, may, must, nor, only, other, our, own, say, some, than, their, them, this, wants, what, which, while, whom, why, would, you,yet

你可以注意到,yet 应该在你之前,所以出了什么问题???

最佳答案

您应该在排序之前删除空格:

var input = 'yet, must, has, wants, would, some, are, let, own, can, could, which, his, had, got, our, only, also, every, after, other, may, you, them, while, ever, what, get, its, why, their, her, him, just, say, this, than, have, able, least, like, whom, nor, cannot, into, among';
input = input.replace(/\s+/g, '').split(',').sort();
console.log(input);

关于javascript 排序不能正确处理字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39430463/

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