Javascript-为什么最后一个字符串字符没有被给定的方法替换(在描述中)?

时间:2017-11-08 17:48:27

标签: javascript

为什么以下两行不会用句号替换最后一个逗号,而是选择不同的位置。我使用了rejected.textContent [rejected.textContent.length -1]来选择最后一个字符串字符,但显然没有选择最后一个字符。有什么问题?

refused.textContent = refused.textContent.replace(refused.textContent[refused.textContent.length -1],".");
    admitted.textContent = admitted.textContent.replace(admitted.textContent[refused.textContent.length -1],"."); 

输出:

承认:.Chris,Anne,Colin,Terri,Sam,Kay,Bruce,

拒绝:.Phil,萝拉,

完整的参考代码:

<!DOCTYPE html>
    <html>
    <head>
    <title>Page Title</title>
    </head>
    <body>
    <div class="output" style="height: 100px;overflow: auto;">
      <p class="admitted">Admit: </p>
      <p class="refused">Refuse: </p>
    </div>
    <script>
    var people = ['Chris', 'Anne', 'Colin', 'Terri', 'Phil', 'Lola', 'Sam', 'Kay', 'Bruce'];

    var admitted = document.querySelector('.admitted');
    var refused = document.querySelector('.refused');

    admitted.textContent = 'Admit: ';
    refused.textContent = 'Refuse: '
    var i = 0;

    do {
      if(people[i] === 'Phil' || people[i] === 'Lola') {
        refused.textContent += people[i] + ', ';
      } else {
        admitted.textContent += people[i] + ', ';
      }
      i++;
    } while(i < people.length);

    refused.textContent = refused.textContent.replace(refused.textContent[refused.textContent.length -1],".");
    admitted.textContent = admitted.textContent.replace(admitted.textContent[refused.textContent.length -1],".");

    </script>
    </body>
    </html>

1 个答案:

答案 0 :(得分:0)

有点猴子补丁。为什么不将数组过滤成两个这样的数组:

const accept = ["Phil","Lola"];
const admit = [], refuse = [];
for(const person of people)
  (accept.includes(person) ? admit : refuse).push( person);

因此,要获得逗号分隔列表,我们只需加入并在末尾添加一个点:

admitted.textContent = admit.join(",") + ".";
refused.textContent = refuse.join(",") + ".";