【问题标题】:How can I create a function that sorts the string according to the integer(1-9) in that string?如何创建一个根据该字符串中的整数(1-9)对字符串进行排序的函数?
【发布时间】:2021-07-11 11:54:15
【问题描述】:

你好 stackoverflow 社区!我再次陷入javascript问题。有人可以请教吗?

函数order 应该接受像"is2 Thi1s T4est 3a" 这样的字符串作为输入,并将返回"Thi1s is2 3a T4est"。每个单词都有一个整数(1-9),我应该对该字符串进行排序。出于某种原因,我的代码没有相应地对单词进行排序,仍然将其返回为 'is2 Thi1s T4est 3a'

这是我的代码:

function order(words){
  let newStr = words.split(" ").sort(function(x,y){
    return parseInt(x) - parseInt(y);
  }).join(" ");
  return newStr;
};

【问题讨论】:

  • 尝试parseInt(x.replace(/[\D]+/g, ''))y 相同
  • ooo 我看到删除所有字符并留下整数

标签: javascript


【解决方案1】:

parseInt 不起作用,因为它只会返回 NaN

你可以match用正则表达式对号码进行排序。

const str = 'is2 Thi1s T4est 3a';
const regex = /\d/;
const arr = str.split(' ');

arr.sort((a, b) => {
  return a.match(regex) - b.match(regex);
});

console.log(arr.join(' '));

【讨论】:

    【解决方案2】:

    我发现了这种非常简单的方法,使用变量,也许其他解决方案更好,但无论如何我都会添加它,以防万一

    function order(words){
      let newStr = words.split(" ").sort(function(x,y){
        let n1, n2
        x.split('').forEach((el) => {
          if(!isNaN(el))
            n1 = el
        })
        
        y.split('').forEach((el) => {
          if(!isNaN(el))
            n2 = el
        })
    
        if(n1 < n2)
          return -1;
        if(n1 > n2)
          return 1;
        return 0;
      })
      return newStr;
    };
    
    console.log(order('is2 Thi1s T4est 3a'))
    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <script src="script.js"></script>
      <title>Document</title>
    </head>
    <body>
      
    </body>
    </html>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-07
      • 1970-01-01
      • 2021-03-27
      • 2021-12-26
      • 2021-10-30
      • 2023-04-05
      • 2017-09-11
      • 2021-08-17
      相关资源
      最近更新 更多