按姓氏的字母顺序对全名字符串进行排序,并以HTML格式显示

时间:2019-06-28 03:38:29

标签: javascript html

今天,在导师的帮助下和一些在线教程中,我们想到了这一点,但我仍然不知道如何以HTML显示它

function compare(a, b) {
  const aName = a.split(" ");
  const bName = b.split(" ");
  const aLastName = aName[aName.length - 1];
  const bLastName = bName[bName.length - 1];
  if (aLastName < bLastName) return -1;
  if (aLastName > bLastName) return 1;
  return 0;
}
const fullNames = "John Mats,Braxton Jackson,Joe Lang,Andre Torrealba,Jonathan Morales";
console.log(fullNames);
const fullNamesArray = fullNames.split(",");
console.log(fullNamesArray);
fullNamesArray.sort(compare);
document.getElementById(nameList).innerHTML = fullNamesArray();
<html>

<body>
  <ol id=#nameList></ol>
</body>
<script src="./script.js"></script>

</html>

3 个答案:

答案 0 :(得分:0)

javascript 的末尾添加此内容:

for(var i = 0;i < fullNamesArray.length;i++)
{
document.getElementById("nameList").innerHTML += "<li>" + fullNamesArray[i] + "</li>";
}

答案 1 :(得分:0)

尝试以下方法,它将迭代并为每个值添加列表标记,并将其分配 v

ar str = '<ul>'

fullNamesArray.forEach(function(f) {
  str += '<li>'+ f + '</li>';
}); 

str += '</ul>';
document.getElementById("nameList").innerHTML = str;

答案 2 :(得分:0)

您需要将数组元素包装在C:\ProgramFiles\Docker\Docker\Resources\bin标签内,然后推入li标签。尝试下面的代码可能就是您想要的。

ul
function compare(a, b) {
  const aName = a.split(" ");
  const bName = b.split(" ");
  const aLastName = aName[aName.length - 1];
  const bLastName = bName[bName.length - 1];
  if (aLastName < bLastName) return -1;
  if (aLastName > bLastName) return 1;
  return 0;
}
var liHtml = "";
const fullNames = "John Mats,Braxton Jackson,Joe Lang,Andre Torrealba,Jonathan Morales";
const fullNamesArray = fullNames.split(",");
fullNamesArray.sort(compare);
fullNamesArray.forEach(function(f) {
  liHtml += '<li>'+ f + '</li>';
}); 
document.getElementById('#nameList').innerHTML = liHtml;