17、数组的去前缀排序

目的

为这些字符串排序,要求去除字符串中的TheA以及An的前缀后再进行排序,并把排序后的结果作为列表项展示在无序列表中。

过程

1.声明去前缀函数,使用String.replace()函数实现,第一参数使用字面量正则表达式。

function delPrefix(item){
    return item.replace(/^(The|A|An)\s{1}/,'');
}

2.使用Array.sort()对数组进行排序,将数组中逐项使用delPrefix()去掉前缀后再进行对比。

var sortedbands = bands.sort(function(a,b){
    return delPrefix(a) > delPrefix(b) ? 1 : -1;
});

3.使用选择器选中无序列表#bands,将排序后的数组作为列表项插入其中。

 document.getElementById('bands').innerHTML = '<li>'+arr.join('</li><li>')+'</li>';

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Sort Without Articles</title>
</head>
<body>

  <style>
    body {
      margin: 0;
      font-family: sans-serif;
      background: url("https://picsum.photos/2000/2000");
      background-size: cover;
      display: flex;
      align-items: center;
      min-height: 100vh;
    }

    #bands {
      list-style: inside square;
      font-size: 20px;
      background: white;
      width: 500px;
      margin: auto;
      padding: 0;
      box-shadow: 0 0 0 20px rgba(0, 0, 0, 0.05);
    }
    #bands li {
      border-bottom: 1px solid #efefef;
      padding: 20px;
    }
    #bands li:last-child {
      border-bottom: 0;
    }

    a {
      color: #ffc600;
      text-decoration: none;
    }

  </style>

  <ul id="bands"></ul>

<script>
  // 去掉 The A An 的前缀 然后排序输出
const bands = ['The Plot in You', 'The Devil Wears Prada', 'Pierce the Veil', 
'Norma Jean', 'The Bled', 'Say Anything', 'The Midway State', 'We Came as Romans', 
'Counterparts', 'Oh, Sleeper', 'A Skylit Drive', 'Anywhere But Here', 'An Old Dog'];

function delPrefix(item){
    return item.replace(/^(The|A|An)\s{1}/,'');
}
var sortedbands = bands.sort(function(a,b){
    return delPrefix(a) > delPrefix(b) ? 1 : -1;
});
document.getElementById('bands').innerHTML = '<li>'+sortedbands.join('</li><li>')+'</li>';
</script>

</body>
</html>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值