Javascript,向字符串添加不同的分隔符

对编码很陌生,如果我的词汇量不足,我很抱歉。这是我要实现的功能的确切要求:


如果一个单词的长度为五个或更多字母,则在单词末尾添加“-bork”


如果一个单词的长度少于五个字母,则在单词末尾添加“-boink”


例如:“The quick brown fox”变成“The-boink quick-bork brown-bork fox-boink”


这是我到目前为止...


 <!DOCTYPE html>

<html>

  <head>

    <script>

      var string = prompt("Enter a string");

      var array = string.split(" ");

      var length = array.map(function (word) {

        return word.length;

      });

      var langauge = array.join("-bork ");

      alert(langauge);

    </script>

  </head>

  <body></body>

</html>

任何帮助表示赞赏!


陪伴而非守候
浏览 188回答 5
5回答

BIG阳

您可以使用后缀映射单词并加入数组以获取字符串。function append(string) {&nbsp; &nbsp; return string&nbsp; &nbsp; &nbsp; &nbsp; .split(' ')&nbsp; &nbsp; &nbsp; &nbsp; .map(s => s + (s.length < 5 ? '-boink' : '-bork'))&nbsp; &nbsp; &nbsp; &nbsp; .join(' ');}console.log(append('The quick brown fox'));

摇曳的蔷薇

像这样做。var string = "The quick brown fox";var array = string.split(" ");var langauge = array.map(function(word) {&nbsp; return word.length < 5 ? `${word}-boink` : `${word}-bork`;}).join(" ");alert(langauge);

扬帆大鱼

String.split您可以使用,Array.join和 来完成Array.map。const input = 'The quick brown fox';const output = input.split(' ').map(item => item.length >= 5 ? item.concat('-bork') : item.concat('-boink')).join(' ');console.log(output);

收到一只叮咚

&nbsp; var string = prompt("Enter a string");&nbsp; var array = string.split(" ");&nbsp; var newArr = array.map(function (word) {&nbsp; return word+"-"+(word.length>=5?"bork":"boink")&nbsp; });&nbsp; var langauge = newArr.join(" ");&nbsp; alert(langauge);

哆啦的时光机

根据您的代码。<!DOCTYPE html><html>&nbsp; <head>&nbsp; &nbsp; <script>&nbsp; &nbsp; &nbsp; var string = prompt("Enter a string");&nbsp; &nbsp; &nbsp; var array = string.split(" ");&nbsp; &nbsp; &nbsp; var length = array.map(function (word) {&nbsp; &nbsp; &nbsp; var langauge;&nbsp; &nbsp; &nbsp; &nbsp; console.log(word.length)&nbsp; &nbsp; &nbsp; &nbsp; if(word.length>=5)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; langauge=word+"-bork"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return langauge&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; else&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; langauge=word+"-boink"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return langauge&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; var finalword= length.join(" ");&nbsp; &nbsp; &nbsp; alert(finalword);&nbsp; &nbsp; </script>&nbsp; </head>&nbsp; <body></body></html>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript