gpt4 book ai didi

javascript - 使用 Javascript 将动态名称字符串列表转换为可排序数组

转载 作者:行者123 更新时间:2023-12-03 10:18:47 27 4
gpt4 key购买 nike

我看过几篇关于如何使用 .split() 将字符串转换为数组的帖子,但我很好奇每次添加新字符串时如何让列表重新排序。

例如,我有一个输入框,我以“名字、姓氏”的格式输入姓名。在按钮单击事件中,输入 div 被清除,生成输入名称的动态列表,并将它们重新格式化为“最后,第一个”。

每次输入新名称时,列表都应按字母顺序排列。

我会让这个输出 div 在每个名称后面的分隔符上分割自身,以便该列表是一个索引字符串数组,但我没有要分割的分隔符。

这是到目前为止我的代码。我知道我可以采取一些措施来改进这一点,但我正在寻找一个非常简单的答案,将这些值存储在数组中而不是字符串列表中,以便它们可以按字母顺序排序。

假设所有数据都以“First Last”格式输入,包括大小写。

全部大写的注释涉及需要变成数组的“combine”变量。

 var namesArr = [];//create an empty array that will hold the names

var output = document.getElementById('output');//get the output element (text area).

var name = document.getElementById('name');//get the textbox

function init(){
var nameBtn = document.getElementById('addNameBtn');//get the name button element

var clrBtn = document.getElementById('clearBtn');//get the clear button element

nameBtn.onclick = enterName;//set up your events here

clrBtn.onclick = clearNames;//set up your events here
}

function enterName(){

if(document.getElementById('name').value !==""){

var arr = document.getElementById('name').value.split(" ");
var space = ", ";
var firstname = arr[1];
var lastname = arr[0];
var outputA = [];
var combine = outputA+firstname+space+lastname+"\n";

output.value += combine//I NEED THIS OUTPUT VALUE
//TO BE STORED IN AN ARRAY
//EVERY TIME A NEW STRING IS ENTERED
//SO THAT I CAN USE .sort() on the array.


}
else{
alert("Please enter a name in the format 'First Last'");
}

if(document.getElementById('name').value !==""){

document.getElementById('name').value = "";//clear names input

}

}

function clearNames(){
document.getElementById('name').value = "";//clear names input
document.getElementById('output').value = "";//clear output input
}

init();//this will run when after the DOM loads

非常感谢您的帮助或反馈。

最佳答案

您可以使用.push()函数将新名称附加到数组中,然后对字符串进行排序。使用您定义的数组 var nameArr = [];

namesArr.push(newLastFirstName);

namesArr.sort();

然后你就可以对排序后的数组做你想做的事情了。 (在本例中将列表输出到 textarea 元素。)

示例:

var namesArr = [
"Smith, John",
"Philip, Bill",
"Power, Max",
"Bar, Foo"
];

// Once the name has been converted ("First Last" -> "Last, First")
// Append the name to the names array
namesArr.push("McFly, Marty");

// (Re-)sort the array since the new element has been added
namesArr.sort();

for(var i = 0; i < namesArr.length; i++) {
console.log(namesArr[i]);
}

输出:

Bar, Foo
McFly, Marty
Philip, Bill
Power, Max
Smith, John

关于javascript - 使用 Javascript 将动态名称字符串列表转换为可排序数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29737488/

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